下面的代码段有什么问题?

2024-04-19 03:46:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试用《编程集体智能》一书中的一些代码,构建一个文档分类器,我遇到了这个由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'

Tags: theinpyselfdeftraincatcc
1条回答
网友
1楼 · 发布于 2024-04-19 03:46:29

^{} exception告诉您字典没有这样的键:

Raised when a mapping (dictionary) key is not found in the set of existing keys.

看看代码,似乎

self.fc.setdefault(cat,0)

应该是

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

相关问题 更多 >