未找到Python方法,但已在类中定义
我正在自学(可能是我的第一个错误)课程和方法,通过转换情绪分析脚本来使用它们 我以为我已经准备好了所有的方法,但我一直在努力未找到Python方法,但已在类中定义,python,python-2.7,Python,Python 2.7,我正在自学(可能是我的第一个错误)课程和方法,通过转换情绪分析脚本来使用它们 我以为我已经准备好了所有的方法,但我一直在努力 未定义全局名称“get\u bigram\u word\u feats” 我敢肯定,如果它走得那么远的话,我的get\u word\u壮举也会出错 我的头撞到了这一次。我尝试删除staticmethod并添加self。我做错了什么 这是我的密码: def word_feats(words): return dict([(word, True) for word i
未定义全局名称“get\u bigram\u word\u feats”
我敢肯定,如果它走得那么远的话,我的get\u word\u壮举也会出错
我的头撞到了这一次。我尝试删除staticmethod
并添加self。我做错了什么
这是我的密码:
def word_feats(words):
return dict([(word, True) for word in words])
class SentClassifier:
def __init__(self, name, location):
self.name = name
self.location = location
self.fullpath = location + "/" + name
def doesexist(self):
return os.path.isfile(self.fullpath)
def save_classifier(self):
rf = open(self.fullpath, 'wb')
pickle.dump(self.fullpath, rf)
rf.close()
def load_classifier(self):
sf = open(self.fullpath, 'rb')
sclassifier = pickle.load(sf)
sf.close()
return sclassifier
class Training:
def __init__(self, neg, pos):
self.neg = neg
self.pos = pos
self.negids = open(self.neg, 'rb').read().splitlines(True)
self.posids = open(self.pos, 'rb').read().splitlines(True)
self.exclude = set(string.punctuation)
self.exclude = self.exclude, '...'
self.swords = stopwords.words('english')
def tokens(self, words):
words = [w for w in nltk.word_tokenize(words) if w not in self.exclude and len(w) > 1
and w not in self.swords and wordnet.synsets(w)]
return words
def idlist(self, words):
thisidlist = [self.tokens(tf) for tf in words]
return thisidlist
@staticmethod
def get_word_feats(words):
return dict([(word, True) for word in words])
@staticmethod
def get_bigram_word_feats(twords, score_fn=BigramAssocMeasures.chi_sq, tn=200):
words = [w for w in twords]
bigram_finder = BigramCollocationFinder.from_words(words)
bigrams = bigram_finder.nbest(score_fn, tn)
return dict([(ngram, True) for ngram in itertools.chain(words, bigrams)])
@staticmethod
def label_feats(thelist, label):
return [(get_word_feats(lf), label) for lf in thelist]
@staticmethod
def label_grams(thelist, label):
return [(get_bigram_word_feats(gf), label) for gf in thelist()]
@staticmethod
def combinegrams(grams, feats):
for g in grams():
feats.append(g)
return feats
def negidlist(self):
return self.idlist(self.negids)
def posidlist(self):
return self.idlist(self.posids)
def posgrams(self):
return self.label_grams(self.posidlist, 'pos')
def neggrams(self):
return self.label_grams(self.negidlist, 'neg')
def negwords(self):
return self.label_feats(self.negidlist, 'neg')
def poswords(self):
return self.label_feats(self.posidlist, 'pos')
def negfeats(self):
return self.combinegrams(self.neggrams, self.negwords)
def posfeats(self):
return self.combinegrams(self.posgrams, self.poswords)
starttime = time.time()
myclassifier = SentClassifier("sentanalyzer.pickle", "classifiers")
if myclassifier.doesexist() is False:
print "training new classifier"
trainset = Training('data/neg.txt', 'data/pos.txt')
negfeats = trainset.negfeats()
posfeats = trainset.posfeats()
negcutoff = len(negfeats) * 8 / 10
poscutoff = len(posfeats) * 8 / 10
trainfeats = negfeats[:negcutoff] + posfeats[:poscutoff]
testfeats = negfeats[negcutoff:] + posfeats[poscutoff:]
print 'train on %d instances, test on %d instances' % (len(trainfeats), len(testfeats))
classifier = NaiveBayesClassifier.train(trainfeats)
print 'accuracy:', nltk.classify.util.accuracy(classifier, testfeats)
myclassifier.save_classifier()
else:
print "using existing classifier"
classifier = myclassifier.load_classifier()
classifier.show_most_informative_features(20)
mystr = "16 steps to an irresistible sales pitch, via @vladblagi: slidesha.re/1bVV7OS"
myfeat = word_feats(nltk.word_tokenize(mystr))
print classifier.classify(myfeat)
probd = classifier.prob_classify(myfeat)
print probd.prob('neg')
print probd.prob('pos')
donetime = time.time() - starttime
print donetime
未定义全局名称“get\u bigram\u word\u feats”
您的调用应如下所示(注意此处使用的类名):
通常,对于静态方法,使用类名
我尝试删除staticmethod并添加self。我做错了什么
在这种情况下,您将使用self.funcName(..)
。如下所示:
def label_grams(self, thelist, label):
return [(self.get_bigram_word_feats(gf), label) for gf in thelist()]
好消息:解决方法很简单。可以这样说:训练。获得单词专长(…)
例如:
您需要的所有信息都在异常消息中:
全局未定义名称“get\u bigram\u word\u feats”
(我的重点)
Python不理解您希望从类访问该方法,因为您没有将类名指定为方法调用的一部分。因此,它正在全局命名空间中查找函数,但未能找到它
如果您还记得调用实例方法,则需要在方法前面加上self.
,以使Python解释器看起来在正确的位置,这也适用于静态方法,尽管您没有指定self.
,而是指定类名
因此,要解决此问题,请在方法调用前加上类名:
return [(Training.get_bigram_word_feats(gf), label) for gf in thelist()]
^---+---^
|
+-- you need this part
我应该指出——我知道我的代码可能很可怕。我的计划是,一旦我开始工作,就开始整合/清理。我知道这不是最好的技术,但是……(可能是我的第一个错误),不,恰恰相反。学习一些东西(包括编程)的最好方法是实验。既然电脑是如此宽容(在这里做实验时,你很少会失去一条腿),那就疯狂吧!FWIW,在这里,classmethod比staticmethod更有意义-您可以访问该类,并且不必在labelgrams
中硬编码类名。作为一般规则,要么你想把方法绑定到一个类,然后把它变成一个classmethod,要么它实际上没有被重写的意义,你只需要使用一个普通函数(是的,这是一个“一般”规则,如果你不知道的话,这是一种指导原则)。
@staticmethod
def label_grams(thelist, label):
return [(Training.get_bigram_word_feats(gf), label) for gf in thelist()]
return [(Training.get_bigram_word_feats(gf), label) for gf in thelist()]
^---+---^
|
+-- you need this part