我正在编写一个程序,它将接受文本作为输入。
程序的值“ tone”从0开始。
当看到该文本中的一个单词(也位于单词“ posfeats”列表中)时,色调会以+1递增。
当看到该文本中的单词(也包含单词“ neffeats”)时,该音调将以-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
最佳答案
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
电话吗? negfeats
和posfeats
是(word, 'neg')
和(word, 'pos')
元组的列表。 compare
将在这些列表中搜索单词,但找不到任何单词,因为单词嵌套在元组中。当然,最好将set
用于没有重复的无序集合。关于python - Python增量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21035950/