【问题标题】:Run StreamListener (Tweepy) and analyze tweets simultaneously运行 StreamListener (Tweepy) 并同时分析推文
【发布时间】:2017-09-04 17:42:33
【问题描述】:

我目前正在使用 Tweepy 流式传输推文,并将每条推文输出到一个 json 文件中。听完并关闭流后,我正在分析推文的情绪。我想知道是否有办法同时做到这一点。我想启动流,在 json 文件中输出推文,然后对该推文运行我的情绪分析,然后对每条推文实时进行一次又一次的分析。

def on_status(self, status):
    self.output.write(status + "\n")

    self.counter += 1

    if self.counter >= 20000:

        self.output.close()
        self.output = open('../streaming_data/' + self.fprefix + '.' + time.strftime('%Y%m%d-%H%M%S') + '.json', 'w')

上面是我的流监听器。输出文件为 self.output。

tweets = {}

with open(output.json, 'r') as file:
    lines = (line.rstrip() for line in file)
    lines = (line for line in lines if line)

    for line in lines:
        tweet = json.loads(line)
        tweets[tweet['id']]= tweet

以上是我将每条推文存储在推文中的方式,以便我可以使用函数对其进行分析。我的函数将推文作为参数。

function = myFunction(tweets, pos, neg)

本质上,StreamListener 收集推文并将它们存储在 json 文件中。但是我想收集推文并在收到推文后立即对其进行分析。所以收集一条推文,然后分析它,然后再做一次。

【问题讨论】:

    标签: python twitter stream tweepy


    【解决方案1】:

    您将推文存储为 json 文件是否有任何具体原因?为什么不简单地将推文文本存储为文本文件,因为我假设您只是对推文的文本进行分析。另外,为什么不调用一个函数来处理推文并让它同时写入文件呢?

    可能如下所示:

    import tweepy
    import secrets
    
    
    class MyStreamListener(tweepy.StreamListener):
        def on_status(self, status):
            process_tweet(status.text)
    
    
    def process_tweet(tweet):
        with open('tweets.txt', 'w') as tweet_file:
            tweet_file.write(tweet)
            sentiment_analysis(tweet)
    
    
    def sentiment_analysis(tweet):
        #code to determine the sentiment of a tweet
    

    您应该使用 async 参数在另一个线程中执行流:

    aStream.filter(track=[aFilter], async=True)
    

    aStream.userstream(async=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-11
      • 2018-08-13
      • 2018-01-06
      • 2015-07-08
      • 2022-10-16
      • 2013-05-05
      • 2012-07-23
      • 1970-01-01
      相关资源
      最近更新 更多