I am trying to count words in a file 'xxxx' by building a dictionary wherein the keys are the words and the values are the number of occurences. So far I got this:
fil = open("xxxx","r")
X = fil.read()
count = {}
for key in X.split():
count[key] += 1
for i in count:
print (i, count[i])
When I run this, I get:
Traceback (most recent call last):
File "countword.py", line 9, in <module>
count[key] = count[key] + 1
KeyError: 'From'
'From' is the first word in the file and since there is no key 'From' up until now, I believe is the cause of the error. But what is the right way to do this? ALso do I need to initialise the value somehow before getting into the for loop?