0
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.

1
  • 1
    Why would you imagine corpus is defined where you are calling getType, i.e. in probWithLapalce. I don't see it defined anywhere. Commented Sep 28, 2017 at 22:58

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.