Skip to main content
 首页 » 编程设计

Python递增

2025年05月04日14bonelee

我正在编写一个接受文本作为输入的程序。

程序有一个从 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 

请您参考如下方法:

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。