我希望跟踪包含某一组单词的tweet,但不包含其他单词。例如,如果我的过滤器是:"taco"AND("chicken"OR"beef")
它应该返回这些tweet:
-I am eating a chicken taco.
-I am eating a beef taco.
它不应该返回这些tweet:
-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"])
它将返回包含这三个单词中的任何一个的所有tweet。我还尝试过其他方法,比如:
twitterStream.filter(track=(["taco"&&("chicken","beef")])
返回语法错误。
我对Python和Tweepy都很陌生。这个和这个看起来都是类似的查询,但它们与同时跟踪多个术语有关,而不是跟踪包含一个术语的tweet子集。我没能在tweepy文档中找到任何东西。
我知道另一种选择是跟踪所有包含"taco"的推文,然后通过"chicken"或"beef"过滤到我的数据库中,但我担心如果我进行一般搜索,然后在Python中过滤它,会遇到1%的流媒体率限制,所以我更喜欢首先从Twitter中传输我想要的术语。
Thanks in advance-
山姆Twitter不允许您非常精确地匹配关键字。但是,跟踪参数文档指出关键字中的空格等同于逻辑上的and。您所指定的所有条款都将合并在一起。
因此,为了实现"taco" AND ("chicken" OR "beef")
的示例,您可以尝试参数[taco chicken
, taco beef
]。这将匹配包含单词taco
和chicken
,或taco
和beef
的tweet。然而,这并不是一个完美的解决方案,因为包含taco
, chicken
和beef
的tweet也会被匹配。