【发布时间】: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