2014-02-11 109 views
0

我正在嘗試運行情緒分析。我已經設法通過nltk使用樸素貝葉斯分類負面和正面推文的語料庫。但是我不想每次運行這個程序時都要運行這個分類器,所以我嘗試使用pickle來保存,然後將分類器加載到不同的腳本中。然而,當我嘗試運行它返回錯誤NameError腳本:名稱分類沒有定義,但我認爲這是通過高清load_classifier()定義:使用Pickle加載分類器?

我有個大氣壓下面的代碼是:

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是'+ classifier.classify(feature_extractor(input))+'在該句子中。\ n'「在返回錯誤之前...

回答

1

那麼,你有宣佈和定義load_classifier()方法,但從來沒有調用它, 分配給一個使用它的變量。這意味着,到時候,執行到達print '\nSentiment is... '行,沒有變量名稱classifier。自然,執行會拋出異常。

在while循環之前添加行classifier = load_classifier()。 (沒有任何縮進)