尽管有关键字,但在python中的Keyerror

时间:2014-06-28 19:52:40

标签: python python-2.7 nltk

我在运行以下程序后获得KeyError:'Fellow',尽管text4中存在此关键字。

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

  print cnt['citizen']

错误:

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

然而,如果我这样做,我可以看到&#39; Fellow&#39;关键字实际上存在。

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

有人可以建议我做错了吗?

1 个答案:

答案 0 :(得分:0)

'Fellow'存在text4但{strong> 存在于cnt中,这是一个没有键的空字典。最小的修复是:

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

但使用collections.Counter可能更容易:

from collections import Counter

cnt = Counter(text4)