[Solved] open .txt file and place every word within a dictionary [closed]


The simple way to get a count of unique words is to use a set. I put your text into a file called ‘qdata.txt’.

The file is very small, so there’s no need to read it line by line: just read the whole thing into a single string, then split that string on whitespace and pass the resulting list into the set constructor:

fname="qdata.txt"
with open(fname) as f:
    words = set(f.read().split())
print(words, len(words))

output

set(['towel', 'onion', 'nandos', 'calculator', 'pigeon', 'dog', 'cat', 'tiger', 'lion', 'cheeky', 'elephant', 'peg', 'fish']) 13

This works because “a set object is an unordered collection of distinct hashable objects”. If you try to add a duplicate item to a set it’s simply ignored. Please see the docs for further details.


For larger files, it is a good idea to read and process them line by line to avoid loading the whole file into RAM, but with modern OSes the file needs to be rather large before you see any benefit, due to file caching.

fname="qdata.txt"
words = set()
with open(fname) as f:
    for line in f:
        words.update(line.split())

print(words, len(words))

solved open .txt file and place every word within a dictionary [closed]