So, my code reads a poem from a file. It then counts the number of time a word occurs and adds to a dictionary. However, my code repeats the words and counts separately.
Here is my code:
def unique_word_count(file):
words = open(file, "r")
lines = words.read()
words = lines.split()
counts = dict()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
For, example if we have the string, "Hi, hi, hi how are you"
:
The output for my code would come out as:
{"Hi":1, "hi":1, "hi":1, "how":1, "are":1, "you":1}
While it should come out as:
{"hi":3, "how":1, "are":1, "you":1}
How can I fix my code so that it does not repeat words? Thank you!