【问题标题】:What is wrong with the following code snippet?以下代码片段有什么问题?
【发布时间】:2026-02-11 14:35:01
【问题描述】:

我目前正在尝试“编程集体智能”一书中的一些代码,构建一个文档分类器,我遇到了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'

【问题讨论】:

标签: python python-2.7 machine-learning artificial-intelligence


【解决方案1】:

KeyError exception 告诉你字典没有这样的键:

在现有键集中找不到映射(字典)键时引发。

看代码,好像

self.fc.setdefault(cat,0)

应该是

self.fc[f].setdefault(cat,0)

【讨论】: