The problem given is that I have been given a file with some text. I have to count the number of times all the word occurs.
What I have tried so far:
def print_words(filename):
input_file = open(filename, 'r')
words = input_file.read().split()
result = {}
for word in words:
if word in result:
result.update({word:1})
else:
result[word] += 1
for count in result:
print(count + ' => ' + str(result[count]))
The error I am getting:
File "wordcount.py", line 50, in print_words
result[word] += 1
KeyError: 'We'
Any help will be really appreciated.