[英]Python, tweepy stream
我正在使用与以下类似的代码,来自: 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'])
你没有提到的第三种可能性:一个鸣叫同时符合“加拿大”和“美国”。 尽管如此,解决方案仍然只是测试推文中是否存在两个或两个过滤词。 所以:
def on_data(self, data):
text = data.text.lower()
if "canada" in text:
do_canada()
if "usa" in text:
do_usa()
return True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.