Reputation: 51
I had just started with Python and have no real programming experience except SQL.
My task:
All punctuations and uppercase are removed so we dont need to worry about that. However, it is several words on the same line
The output should look something like this
Common words on both lines: ['I', 'the', 'am', 'all', 'as', ...]
Only even lines : ['yellow', 'christmas', 'smell', ...]
Only odd lines: ['yours', 'war', 'may', 'remote', ...]
I started like
evens, odds = set(), set()
with open('textfile.txt') as f:
for index, row in enumerate(f):
if index % 2 == 0:
evens.update(row.split())
else:
odds.update(row.split())
commons = sorted(evens & odds)
How should I continue from here? My main problem is to print out the unique words for evens and odds. A minor problem is to transpose my list in commons to a row.
Upvotes: 4
Views: 326
Reputation: 31
Firstly, to know the common word in even and odd lines, you need to get two lists of the words of even and odd lines.This is how to make two lists of these.
Then you have to find the common words exists in two lists.If the word is a common word of two lists, delete this word from two lists and add it to the new list of common words.
Upvotes: 0
Reputation: 571
List comprehension is an important concept to learn, if you want to use python regularly.
So you can try for problem statement 1:
combine=['I', 'the', 'am', 'all', 'as','yellow']
even_line=['yellow', 'christmas', 'smell']
odd_line=['yours', 'war', 'may', 'remote','yellow']
words_in_both_odd_even=[i for i in combine for j in even_line for k in odd_line if (i==j and i==k)]
words_in_both_odd_even
For problem statement 2:
words_in_even_line=[i for i in combine for j in even_line if (i==j)]
words_in_even_line
For problem statement 3:
words_in_odd_line=[i for i in combine for k in odd_line if (i==k)]
words_in_odd_line
If you are looking for unique values in any of the above there problem statement output- Then you can use set(words_in_both_odd_even)
or set(words_in_even_line)
or set(words_in_odd_line)
Upvotes: 0