-2

Find all unique words in a file Shakespeare used over 20,000 words in his works. Download a copy of the file www.py4e.com/code3/romeo.txt (https://www.py4e.com/code3/romeo.txt). Write a program to 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 function. For each word, check to see if the word is already in the list of unique words. If the word is not in the list of unique words, add it to the list. When the program completes, sort and print the list of unique words in alphabetical order

fhand = open("romeo.txt", "r+")
    for line in fhand:
         words = line.split()
         for word in words:
             if word in words:
                 continue
             elif word not in words:
                 words.append(word)
                 continue
            continue
        words.sort()
        print("words") 
azro
  • 53,056
  • 7
  • 34
  • 70
  • What is the problem you face ? – azro Mar 19 '22 at 10:19
  • It is not at all clear what the question is: what would you like help with? It would be really helpful if you could format that python snippet as a python snippet, so that we can read it properly. – soothsooth Mar 19 '22 at 10:19
  • Your code is a good start. Issues I see: 1) superfluous continue statements, 2) not removing whitespaces at end of lines, 3) elif unnecessary--in this case just use else without condition. To see how to how to improve your code check out [How to read a file line-by-line into a list](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list). – DarrylG Mar 19 '22 at 10:28
  • This looks like an assignment from school or whatever. If you face a specific problem, please clarify it, else, this stack is not about doing your homeworks. – Itération 122442 Jun 29 '23 at 06:54

2 Answers2

0

The words variable written in print statement should be without quotes.

It should be:

print(words)

And also words.sort() and print(words) should be outside the for loop.

Vaibhav Jadhav
  • 2,020
  • 1
  • 7
  • 20
-1
lista = open('romeo.txt')
lista2 = []

for line in lista:
    words = line.split()
    for word in words:
        if word not in lista2:
            lista2.append(word)
        
lista2.sort()
print(lista2)
ArturB
  • 1
  • 1