对 Python 中包含 JSON 元素(推文)的 mongodb 集合执行情感分析



嗨,我创建了一个 python 脚本,使用 tweepy 根据数组中的元素名称将基于关键字数组的推文流式传输到 mongodb 集合中,该元素通过 pymongo 即(Apple 推文保存到 Apple 集合)。此脚本将它们保存为 JSON 格式,现在我想对这些保存的推文执行情绪分析。

我一直在阅读一些关于此的教程,并决定使用内置在 TextBlob 模块中的 NaiveBayesClassifier。我已经创建了一些训练数据并将其传递到分类器中(只是一个普通的文本数组,每个元素的末尾都有情绪),但我不确定如何将这个分类器应用于我已经保存的推文。我认为它如下所示,但这不起作用,因为它会引发错误:

Traceback (most recent call last):
  File "C:/Users/Philip/PycharmProjects/FinalYearProject/TrainingClassification.py", line 25, in <module>
    cl = NaiveBayesClassifier(train)
  File "C:Python27libsite-packagestextblobclassifiers.py", line 192, in __init__
    self.train_features = [(self.extract_features(d), c) for d, c in self.train_set]
ValueError: too many values to unpack

这是我到目前为止的代码:

from textblob.classifiers import NaiveBayesClassifier
import pymongo
train = [
    'I love this sandwich.', 'pos',
    'I feel very good about these beers.', 'pos',
    'This is my best work.', 'pos',
    'What an awesome view", 'pos',
    'I do not like this restaurant', 'neg',
    'I am tired of this stuff.', 'neg',
    'I can't deal with this', 'neg',
    'He is my sworn enemy!', 'neg',
    'My boss is horrible.', 'neg'
]
cl = NaiveBayesClassifier(train)
conn = pymongo.MongoClient('localhost', 27017)
db = conn.TwitterDB
appleSentiment = cl.classify(db.Apple)
print ("Sentiment of Tweets about Apple is " + appleSentiment)

任何帮助将不胜感激。

引用文档

分类:对文本字符串进行分类。

但相反,您正在传递它一个集合。 db.Apple是集合而不是字符串文本。

appleSentiment = cl.classify(db.Apple)
                              ^

您需要编写查询并使用查询结果作为参数来classify例如,查找任何特定的推文都可以使用find_one。有关更多信息,文档是您的朋友。

以下是使用 TextBlob 和 PyMongo 进行情感分析的方法:

from textblob import TextBlob
import re
def clean_tweet(tweet):
    return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z t]) | (w +: /  / S +)", " ", tweet).split())

def tweet_sentiment(tweet):
    tweet_analysis = TextBlob(clean_tweet(tweet))
    if tweet_analysis.polarity > 0:
        return 'positive'
    elif tweet_analysis.polarity == 0:
        return 'neutral'
    else:
        return 'positive'
for tweet in tweets:
    print(tweet_sentiment(tweet['text']), " sentiment for the tweet: ", tweet['text'])

最新更新