我目前正在尝试编写一本名为“#34; Programming Collective Intelligence"”的书中的一些代码,构建一个文档分类器,我遇到了docclass.py
引起的错误。谁能告诉我如何调试这些问题?
def __init__(self,getfeatures,filename=None):
self.fc={}
self.cc={}
self.getfeatures=getfeatures
def incf(self,f,cat):
self.fc.setdefault(f,{})
self.fc.setdefault(cat,0)
self.fc[f][cat]+=1
def incc(self,cat):
self.cc.setdefault(cat,0)
self.cc[cat]+=1
def train(self,item,cat):
features=self.getfeatures(item)
for f in features:
self.incf(f,cat)
self.incc(cat)
我收到以下错误:
>>> import docclass
>>> c1=docclass.classifier(docclass.getwords)
>>> c1.train('the quick brown fox jumps over the lazy dog','good')
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
c1.train('the quick brown fox jumps over the lazy dog','good')
File "docclass.py", line 36, in train
self.incf(f,cat)
File "docclass.py", line 17, in incf
self.fc[f][cat]+=1
KeyError: 'good'
答案 0 :(得分:2)
KeyError
exception告诉你字典没有这样的密钥:
在现有密钥集中找不到映射(字典)密钥时触发。
查看代码,似乎
self.fc.setdefault(cat,0)
应该是
self.fc[f].setdefault(cat,0)