python - NLTK 情绪分析只返回一个值

标签 python twitter nltk sentiment-analysis

我真的很讨厌发布关于整个代码块的问题,但过去 3 个小时我一直在研究这个问题,我无法理解正在发生的事情。我从一个 CSV 文件中检索了大约 600 条推文,这些推文具有不同的分值(在 -2 到 2 之间),反射(reflect)了对总统候选人的情绪。

但是,当我在任何其他数据上运行此训练样本时,只返回一个值(正值)。我已经检查了是否正确添加了分数,它们是正确的。 85,000 条推文从 600 条不同的训练集中全部被评为“正面”对我来说是没有意义的。有人知道这里发生了什么吗?谢谢!

import nltk
import csv

tweets = []
import ast
with open('romney.csv', 'rb') as csvfile:
    mycsv = csv.reader(csvfile)
    for row in mycsv:
        tweet = row[1]
        try:
            score = ast.literal_eval(row[12])
            if score > 0:
                print score
                print tweet
                tweets.append((tweet,"positive"))

        elif score < 0:
            print score
            print tweet
            tweets.append((tweet,"negative"))
    except ValueError:
        tweet = ""

def get_words_in_tweets(tweets):
    all_words = []
    for (words, sentiment) in tweets:
      all_words.extend(words)
    return all_words

def get_word_features(wordlist):
    wordlist = nltk.FreqDist(wordlist)
    word_features = wordlist.keys()
    return word_features

def extract_features(document):
    document_words = set(document)
    features = {}
    for word in word_features:
    features['contains(%s)' % word] = (word in document_words)
    return features

word_features = get_word_features(get_words_in_tweets(tweets))
training_set = nltk.classify.apply_features(extract_features, tweets)
classifier = nltk.NaiveBayesClassifier.train(training_set)
c = 0
with open('usa.csv', "rU") as csvfile:
    mycsv = csv.reader(csvfile)
    for row in mycsv:
        try:
            tweet = row[0]
            c = c + 1
                    print classifier.classify(extract_features(tweet.split()))                                                                                                                                                                                     
        except IndexError:
            tweet = ""

最佳答案

朴素贝叶斯分类器通常在评估文档中出现的词时效果最好,忽略不存在的词。由于您使用

features['contains(%s)' % word] = (word in document_words)

每个文档主要由值为 False 的特征表示。

试试像这样的东西:

if word in document_words:
   features['contains(%s)' % word] = True

(您可能还应该更改 for 循环以获得比遍历词典中的所有单词更有效的东西,而不是循环出现在文档中的单词)。

关于python - NLTK 情绪分析只返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15106032/

相关文章:

python - 如果数据框行为 1,其余值设置为 0,如何设置最大值

python - 如何在 AWS Elastic Beanstalk 中使用 Plotly Python SDK

java - 线程中出现异常 "Twitter4J Async Dispatcher[0]"java.lang.NoClassDefFoundError

c++ - 适用于 iOS 和 Android 的 QT C++ 中的 HTTPS 请求

python - NLTK SVM 分类器终止

python - RESTful API 中使用的 Etag 仍然容易受到竞争条件的影响

python - Windows 上的 Tensorflow contrib.layers 兼容性

python - NLTK NaiveBayesClassifier 在 Python 中非常慢?

facebook - 在 Feeds 架构(如 Facebook 新闻或 Twitter)中,如何使 feeds 计数与 feeds 列表的长度一致?

python - 使用 nltk 对文本文档进行分类