Keyerror in python despite having keyword

I am getting KeyError:'Fellow' after running following program despite this keyword exist in the text4.

  import nltk;
  from nltk.book import *
  cnt = {}
  for word in text4:
       cnt[word] += 1

  print cnt['citizen']

Error:

Traceback (most recent call last):
  File "wordcount.py", line 5, in <module>
    cnt[word] += 1
KeyError: 'Fellow'

However, if I do this I can see that 'Fellow' keyword is in fact present.

  >>> text4.count('Fellow')
      24

Could anyone please suggest what am I doing wrong ?

Answers


'Fellow' exists in text4 but not in cnt, which is an empty dictionary with no keys. The minimal fix is:

for word in text4:
       if word not in cnt:
           cnt[word] = 0
       cnt[word] += 1

But it's probably easier to use collections.Counter:

from collections import Counter

cnt = Counter(text4)

Need Your Help

How to delay .trigger('click') with overlay from jquery tools

jquery ajax overlay

I am using Jquery tools, overlay effect and want to close it, if JSON response is OK, but i want to do it with a delay.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.