class UnigramDist:
def __init__(self, corpus):
self.counts = defaultdict(float)
self.total = 0.0
self.train(corpus)
# Get number of unique words (type)
def getType(self, corpus):
unique = []
for sen in corpus:
for word in sen:
if(word not in unique):
unique.append(word)
return len(unique)
def probWithLapalce(self, word):
V = self.getType(corpus)
word = word.strip()
probVal = (self.counts[word] + 1) / (self.total + V)
return math.log(probVal)
#enddef
我正在创建一个名为UnigramDist的类,它包含一些计算unigram模型概率的方法,我试图在同一类的probWithLaplace方法中使用getType方法。
但是当我在测试中使用这个类时,它会给我一条消息:
V = self.getType(corpus)
NameError: name 'corpus' is not defined
我没有得到它,因为所有其他功能都使用语料库就好了。
答案 0 :(得分:2)
在其他方法中,corpus
作为方法参数传递
def getType(self, corpus):
# ^^^^^^--- method parameter
因此被定义为局部变量。
但是,在probWithLaplace
方法中,语料库既不作为参数传递,也不在本地(在方法体内)定义,也不在全局(模块级别)定义:
# no global (module level) variable corpus ...
def probWithLaplace(self, word): # ... and no corpus here ...
# ... or here
V = self.getType(corpus) # hence, corpus is not defined here
答案 1 :(得分:2)
您的其他函数将corpus
作为参数,因此它是这些函数中的局部变量。
您可以在self.corpus = corpus
函数中设置__init__
,然后使self.corpus
可用于所有该类的函数。 (只要他们知道self
- 也就是说,只要他们重新实例化方法)