Tweepy过滤中的逻辑运算符
我想追踪包含特定单词的推文,但不包括其他单词。比如说,如果我的过滤条件是:“taco”(玉米饼)并且(“chicken”(鸡肉)或者“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都还比较陌生。虽然这个和这个看起来是类似的问题,但它们是关于同时追踪多个词,而不是追踪包含某个词的推文的子集。我在tweepy文档中没有找到相关的信息。
我知道另一种选择是追踪所有包含“taco”的推文,然后在我的数据库中通过“chicken”或“beef”进行过滤,但我担心如果我先做一个一般搜索再在Python中过滤,会遇到1%的流媒体速率限制,所以我更希望一开始就只从Twitter上获取我想要的词。
提前谢谢你们-
Sam
1 个回答
15
Twitter在关键词匹配上并不能让你非常精确。不过,track参数的说明提到,关键词中的空格相当于逻辑上的“与”(AND)。你指定的所有词是“或”(OR)关系。
所以,如果你想实现你的例子 "taco" AND ("chicken" OR "beef")
,你可以试试这些参数:[taco chicken
, taco beef
]。这样的话,会匹配到包含 taco
和 chicken
的推文,或者 taco
和 beef
的推文。不过,这并不是一个完美的解决方案,因为如果有一条推文同时包含 taco
、chicken
和 beef
,它也会被匹配到。