Forums

I cannot find the mistake

I have to solve the following problem: Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.

My programme is:

fname = input("Enter file name: ")
archivo = open(fname, "r")
lista=[]

for line in archivo:
    word=line.split()

        if word not in lista:
            lista.append(word)
        else:
            continue

lista.sort()
print (lista)

And the result is:

[['Arise', 'fair', 'sun', 'and', 'kill', 'the', 'envious', 'moon'], ['But', 'soft', 'what', 'light', 'through', 'yonder', 'window', 'breaks'], ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun'], ['Who', 'is', 'already', 'sick', 'and', 'pale', 'with', 'grief']]

But I should get:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

Any ideas? Thank you in advance

[edit by admin] formatting

These are the forums for PythonAnywhere, so normally we (the admins) can only give tech support on our own system. However, as I spotted the problem while looking at your code, I'll let you know -- in the line

word=line.split()

...you are setting the variable word to a list of all of the words in the line. I recommend that you call that variable words instead, and then do a loop over it, split by spaces:

for word in words.split(" "):

...and put your if statement in there.