How to return unique words from the text file using Python

后端 未结 9 2120
遇见更好的自我
遇见更好的自我 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-04 23:53

    Simply iterate over the lines in the file and use set to keep only the unique ones.

    from itertools import chain
    
    def unique_words(lines):
        return set(chain(*(line.split() for line in lines if line)))
    

    Then simply do the following to read all unique lines from a file and print them

    with open(filename, 'r') as f:
        print(unique_words(f))
    

提交回复
热议问题