Search code examples
pythonpython-3.xlistpython-2.7computer-science

I need to make a function that takes a body of text and outputs a list of all unique words in the text. The output list will contain strings


Here is what I got. It is not working when I run it. Can someone help guide me on what is wrong with my code?

def unique_words(text : str) ->list:
  text = open(text, 'r')
  text_contents = text.read()
  text.close()
  word_list = text_contents.split()

word = open(str, 'w')
unique = []
for word in word_list:
    if word not in word_list:
        file.append(str(word) + "\n")

unique.sort()

return(unique)

Here is my code


Solution

  • Set will hold all unique values. If you add duplicate, then the set will ignore it.

    word_list = ['hello', 'hello', 'world', 'world']
    
    unique = set()
    for word in word_list:
        if word not in unique:
            unique.add(word)
    print(unique)