我在运行以下程序后获得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
有人可以建议我做错了吗?
答案 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)