【问题标题】:Python, tweepy streamPython,tweepy 流
【发布时间】:2018-05-30 20:34:09
【问题描述】:

我正在使用类似于下面的代码,来自:https://github.com/tweepy/tweepy/blob/master/examples/streaming.py

API 允许您跟踪多个过滤条件,在此示例中为 track=['usa','canada']。这实质上意味着该流将收集提及“加拿大”或“美国”的推文。

问题是函数 on_data() 打印数据,但它没有指定数据属于哪个过滤器术语。当您仅按一个术语(例如在 github 页面上提供的示例中)进行过滤时,它是隐式的,但是当您有多个术语时,如何打印术语和与之关联的数据?

换句话说,我如何知道哪些推文被“加拿大”过滤,哪些被“美国”过滤?

from __future__ import absolute_import, print_function

from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream

# Go to http://apps.twitter.com and create an app.
# The consumer key and secret will be generated for you after
consumer_key=""
consumer_secret=""

# After the step above, you will be redirected to your app's page.
# Create an access token under the the "Your access token" section
access_token=""
access_token_secret=""

class StdOutListener(StreamListener):
    """ A listener handles tweets that are received from the stream.
    This is a basic listener that just prints received tweets to stdout.
    """
    def on_data(self, data):
        print(data)
        return True

    def on_error(self, status):
        print(status)

if __name__ == '__main__':
    l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    stream = Stream(auth, l)
stream.filter(track=['usa','canada'])

【问题讨论】:

    标签: python twitter stream tweepy


    【解决方案1】:

    你没有提到第三种可能性:一条推文匹配两个“加拿大”和“美国”。尽管如此,解决方案还是简单地测试推文中是否存在一个或两个过滤词。所以:

    def on_data(self, data):
        text = data.text.lower()
        if "canada" in text:
            do_canada()
        if "usa" in text:
            do_usa()
        return True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      • 1970-01-01
      • 2015-03-06
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多