我正在尝试进行情绪分析。我已经设法通过nltk使用朴素贝叶斯来分类负面和正面推文的语料库。但是我不希望每次运行此程序时都要经历运行此分类器的过程,因此我尝试使用pickle进行保存,然后将分类器加载到不同的脚本中。但是,当我尝试运行脚本时,它返回错误NameError:未定义name分类器,尽管我认为它是通过def load_classifier()定义的:
我的代码如下:
import nltk, pickle
from nltk.corpus import stopwords
customstopwords = ['']
p = open('xxx', 'r')
postxt = p.readlines()
n = open('xxx', 'r')
negtxt = n.readlines()
neglist = []
poslist = []
for i in range(0,len(negtxt)):
neglist.append('negative')
for i in range(0,len(postxt)):
poslist.append('positive')
postagged = zip(postxt, poslist)
negtagged = zip(negtxt, neglist)
taggedtweets = postagged + negtagged
tweets = []
for (word, sentiment) in taggedtweets:
word_filter = [i.lower() for i in word.split()]
tweets.append((word_filter, sentiment))
def getwords(tweets):
allwords = []
for (words, sentiment) in tweets:
allwords.extend(words)
return allwords
def getwordfeatures(listoftweets):
wordfreq = nltk.FreqDist(listoftweets)
words = wordfreq.keys()
return words
wordlist = [i for i in getwordfeatures(getwords(tweets)) if not i in stopwords.words('english')]
wordlist = [i for i in getwordfeatures(getwords(tweets)) if not i in customstopwords]
def feature_extractor(doc):
docwords = set(doc)
features = {}
for i in wordlist:
features['contains(%s)' % i] = (i in docwords)
return features
training_set = nltk.classify.apply_features(feature_extractor, tweets)
def load_classifier():
f = open('my_classifier.pickle', 'rb')
classifier = pickle.load(f)
f.close
return classifier
while True:
input = raw_input('I hate this film')
if input == 'exit':
break
elif input == 'informfeatures':
print classifier.show_most_informative_features(n=30)
continue
else:
input = input.lower()
input = input.split()
print '\nSentiment is ' + classifier.classify(feature_extractor(input)) + ' in that sentence.\n'
p.close()
n.close()
任何帮助都会很棒,脚本似乎会在返回错误之前将它打印到'\ nSentiment is'+ classifier.classify(feature_extractor(input))+'中。\ n'“
答案 0 :(得分:1)
嗯,你已经声明并定义了 load_classifier()
方法,但从未调用过它,使用它来分配变量。这意味着,到时候,执行到达print '\nSentiment is... '
行,没有变量名classifier
。当然,执行会引发异常。
在while循环之前添加行classifier = load_classifier()
。 (没有任何缩进)