【问题标题】:Performing sentiment analysis on a mongodb collection containing JSON elements (tweets) in Python在 Python 中对包含 JSON 元素(推文)的 mongodb 集合执行情感分析
【发布时间】:2015-05-10 17:50:31
【问题描述】:

您好,我创建了一个 python 脚本,使用 tweepy 将基于关键字数组的推文流式传输到 mongodb 集合中,该集合基于数组中通过 pymongo 过滤的元素的名称,即(苹果推文保存到苹果集合)。该脚本将它们保存为 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:\Python27\lib\site-packages\textblob\classifiers.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)

任何帮助将不胜感激。

【问题讨论】:

    标签: python-2.7 pymongo textblob


    【解决方案1】:

    引用documentation

    分类:对一串文本进行分类。

    但是你传递给它的是一个集合。 db.Apple 是一个集合而不是字符串文本。

    appleSentiment = cl.classify(db.Apple)
                                  ^
    

    您需要编写一个查询并将查询结果用作classify 的参数 例如,要查找任何特定的推文,可以使用find_one。如需更多信息,documentation 是您的朋友。

    【讨论】:

      【解决方案2】:

      以下是使用 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'])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-25
        • 1970-01-01
        • 2020-11-01
        • 2020-08-14
        相关资源
        最近更新 更多