How to return unique words from the text file using Python

后端 未结 9 2119
遇见更好的自我
遇见更好的自我 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:11

    This seems to be a typical application for a collection:

    ...
    import collections
    d = collections.OrderedDict()
    for word in wordlist: d[word] = None 
    # use this if you also want to count the words:
    # for word in wordlist: d[word] = d.get(word, 0) + 1 
    for k in d.keys(): print k
    

    You could also use a collection.Counter(), which would also count the elements you feed in. The order of the words would get lost though. I added a line for counting and keeping the order.

提交回复
热议问题