2014-01-10 5 views
2

텍스트를 입력으로 받아들이는 프로그램을 작성 중입니다.파이썬 증분

프로그램은 0에서 시작하는 값 "tone"을가집니다. "posfeats"단어 목록에있는 텍스트에서 단어를 볼 때 +1이 증가합니다. "negfeats"단어 목록에있는 해당 텍스트의 단어를 볼 때 톤이 -1 씩 증가합니다.

그러나 내 코드는 입력 텍스트에 상관없이 "tone"값에 대해 0을 반환합니다. 내 알고리즘보다는 내 잘못 된 Python 프로그래밍 때문인 것 같다.

import nltk.classify.util 
from nltk.classify import NaiveBayesClassifier 
from nltk.corpus import movie_reviews #importing two corpora, movie_reviews and stopwords 
from nltk.corpus import stopwords 

def word_feats(words): 
stops = dict([(word, True) for word in stopwords.words('english')]) #English stopwords 
features = dict([(word, True) for word in words if word not in stops])#features minus stopwords 
return features 

def compare(words, negfeats, posfeats): 
sentiment=0 
for word in words: 
    if word in negfeats: 
     sentiment -= 1 
    if word in posfeats: 
     sentiment += 1 
return sentiment 


negReviews = reviews.fileids('neg') 
posReviews = reviews.fileids('pos') 

negfeats = [(word_feats(reviews.words(fileids=[f])), 'neg') for f in negReviews] 
posfeats = [(word_feats(reviews.words(fileids=[f])), 'pos') for f in posReviews] 

opinion = raw_input("Why don't you tell me about a movie you watched recently?\n\n") 
tone = compare(opinion.split(), negfeats, posfeats) 
print(str(tone)) #THIS KEEPS RETURNING 0 
+0

왜 "tone = 0"을 compare()의 첫 번째 줄에 추가 했습니까? 반환 값에 어떤 영향을 주는지 확신 할 수 없지만, 거기에 있어야한다고 생각하지 않습니다. 대신 '정서 = 0'이어야합니다! –

+1

중복되지 않은 요소의 순서가없는 콜렉션을 원한다면, 무시 된 값을 가진'dict' 대신'set'을 사용하는 것이 더 깔끔합니다. – user2357112

+0

@ Kohler, 네 말이 맞아, 나는 그것을 완전히 stackoverflow에 복사 할 때 잘못 썼다. – Shuklaswag

답변

1
negfeats = [(word_feats(reviews.words(fileids=[f])), 'neg') for f in negReviews] 
posfeats = [(word_feats(reviews.words(fileids=[f])), 'pos') for f in posReviews] 

당신이 여기 dict 통화를 할 찾으 셨나요? 여기

코드인가? negfeatsposfeats(word, 'neg')(word, 'pos') 튜플의 목록입니다. compare은이 목록에서 단어를 검색하고 단어가 튜플에 중첩되어 있기 때문에 찾을 수 없습니다. 물론 중복되지 않은 순서가없는 콜렉션에는 set을 사용하는 것이 좋습니다.

+0

어떤 이유인지, stackoverflow에 복사하는 동안 잘못 입력했습니다. 내 코드는 감정 = 0이라고 말합니다. 하지만 여전히 0 값을 얻고 있습니다 ... – Shuklaswag

+0

@ user3180238 : 다시 입력하지 마십시오. 복사/붙여 넣기가 훨씬 쉽고 안정적입니다. – user2357112

+0

@ user3180238 : 코드의 새 버전을 반영하도록 답변이 업데이트되었습니다. – user2357112