【发布时间】:2018-02-14 20:15:08
【问题描述】:
我希望跟踪包含特定单词集的推文,而不是其他单词。例如,如果我的过滤器是:“taco” AND (“chicken” OR “beef”)。
它应该返回这些推文:
-I am eating a chicken taco.
-I am eating a beef taco.
它不应该返回这些推文:
-I am eating a taco.
-I am eating a pork taco.
这是我目前正在运行的代码:
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import time
import json
# authentication data- get this info from twitter after you create your application
ckey = '...' # consumer key, AKA API key
csecret = '...' # consumer secret, AKA API secret
atoken = '...' # access token
asecret = '...' # access secret
# define listener class
class listener(StreamListener):
def on_data(self, data):
try:
print data # write the whole tweet to terminal
return True
except BaseException, e:
print 'failed on data, ', str(e) # if there is an error, show what it is
time.sleep(5) # one error could be that you're rate-limited; this will cause the script to pause for 5 seconds
def on_error(self, status):
print status
# authenticate yourself
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=["taco"]) # track what you want to search for!
代码的最后一行是我正在努力解决的部分;如果我使用:
twitterStream.filter(track=["taco","chicken","beef"])
它将返回包含这三个单词中的任何一个的所有推文。我尝试过的其他事情,例如:
twitterStream.filter(track=(["taco"&&("chicken","beef")])
返回语法错误。
我对 Python 和 Tweepy 都很陌生。 this 和 this 看起来都是相似的查询,但它们与同时跟踪多个术语有关,而不是跟踪包含术语的推文子集。我在tweepy documentation 中找不到任何内容。
我知道另一种选择是跟踪所有包含“taco”的推文,然后通过“chicken”或“beef”过滤到我的数据库中,但我担心如果我做一个一般的流式传输速率限制会遇到 1%搜索然后在 Python 中对其进行过滤,因此我更喜欢首先从 Twitter 流式传输我想要的术语。
提前致谢-
山姆
【问题讨论】: