2014-02-11 2 views
0

감정 분석을 실행하려고합니다. 나는 nltk를 통해 Naive Bayes를 사용하여 부정적이고 긍정적 인 짹짹의 코퍼스를 분류했습니다. 그러나 나는이 프로그램을 실행할 때마다이 분류자를 실행하는 과정을 밟고 싶지 않으므로 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 is'오류를 반환하기 전에 해당 문장의 \ classifier.classify (feature_extractor (input)) + '를 인쇄하는 것으로 보입니다.

답변

1

음, 이 선언되어 있고load_classifier() 메쏘드가 정의되어 있지만 결코 호출되지 않았습니다. 에는이 사용 된 변수가 지정됩니다. 즉, 실행이 print '\nSentiment is... ' 행에 도달하면 변수 이름이 classifier이 아닙니다. 물론, 실행은 예외를 던집니다.

루프를 추가하는 동안 루프 classifier = load_classifier()을 추가하십시오. (들여 쓰기 없음)

관련 문제