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
I am creating a class called UnigramDist that contains some methods that compute the probability of a unigram model, and I am trying to use the getType method in my probWithLaplace method in the same class.
But when I use this class in my test, it gives me a message that says:
V = self.getType(corpus)
NameError: name 'corpus' is not defined
I don't get it since all other functions are using corpus just fine.
2 Answers 2
In the other methods, corpus is passed as a method parameter
def getType(self, corpus):
# ^^^^^^--- method parameter
and is therefore defined as a local variable.
In your probWithLaplace method, however, corpus is neither passed as an argument, defined locally (inside the method body) nor globally (at module level) before you use it:
# 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
Comments
Your other functions are getting corpus as a parameter, so it's a local variable in those functions.
You could set self.corpus = corpus in your __init__ function, which would then make self.corpus available to all of that class's functions. (as long as they know about self - that is, as long as they're instance methods)
corpusis defined where you are callinggetType, i.e. inprobWithLapalce. I don't see it defined anywhere.