Reputation: 818
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.
Upvotes: 2
Views: 296
Reputation: 122024
When you iterate through your words:
for word in words:
if word in result:
result.update({word:1})
else:
result[word] += 1
You add word
to result
using update
only when it is already there (if word in result:
). If it is not there, you try to add one to its value anyway, which Python can't do, hence the KeyError
.
The minimal fix is either:
if
and else
blocks around; orif word not in result
.Alternatively, you can simplify with collections.defaultdict
:
from collections import defaultdict
result = defaultdict(int)
for word in words:
result[word] += 1
Upvotes: 4
Reputation: 50970
Okay, what's happening is that the variable word
contains the "We". You're trying to increment the counter in the dictionary, but Python is telling you that "We" is not (yet) a key in the dictionary.
This indicates that there's an error in your add-to-dictionary logic and, indeed, looking at the program you only add the word to the dictionary if it's already in the dictionary. Replace
if word in result:
with
if word not in result:
and you'll be on your way.
Upvotes: 1
Reputation: 20361
At the moment, you are saying that if the item is already in the dictionary, set it to 1. But if it doesn't exist, you try to reassign the value. This is obviously the wrong way round.
To fix this, replace:
if word in result:
with:
if word not in result:
There you go, problem solved.
Upvotes: 1