How to return unique words from the text file using Python

后端 未结 9 2182
遇见更好的自我
遇见更好的自我 2021-01-04 23:45

How do I return all the unique words from a text file using Python? For example:

I am not a robot

I am a human

Should return:

9条回答
  •  日久生厌
    2021-01-05 00:01

    Use a set. You don't need to import anything to do this.

    #Open the file
    my_File = open(file_Name, 'r')
    #Read the file
    read_File = my_File.read()
    #Split the words
    words = read_File.split()
    #Using a set will only save the unique words
    unique_words = set(words)
    #You can then print the set as a whole or loop through the set etc
    for word in unique_words:
         print(word)
    

提交回复
热议问题