我希望跟踪包含特定单词的tweet,而不是其他的。例如,如果我的过滤器是:“玉米卷”和(“鸡肉”或“牛肉”)。
它应该返回这些tweets:
-I am eating a chicken taco.
-I am eating a beef taco.
它不应该返回这些tweets:
-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"])
它将返回包含这三个词中任何一个的所有tweets。我尝试过的其他事情,例如:
twitterStream.filter(track=(["taco"&&("chicken","beef")])
返回语法错误。
我对Python和Tweepy都很陌生。this和this看起来都是类似的查询,但它们与同时跟踪多个术语相关,而不是跟踪包含一个术语的tweets子集。我在tweepy documentation里找不到任何东西。
我知道另一个选择是跟踪所有包含“taco”的tweets,然后通过“chicken”或“beef”过滤到我的数据库中,但是如果我做一个常规搜索,然后在Python中过滤掉它,我担心会遇到1%的流传输速率限制,所以我更希望首先从Twitter中传输我想要的术语。
提前谢谢-
山姆
Twitter不允许你非常精确地匹配关键词。然而,track parameter documentation声明关键字中的空格等同于逻辑和。您指定的所有术语都在一起。
因此,为了实现您的
"taco" AND ("chicken" OR "beef")
示例,您可以尝试参数[taco chicken
,taco beef
]。这将匹配包含单词taco
和chicken
,或者taco
和beef
的tweets。然而,这并不是一个完美的解决方案,因为包含taco
、chicken
和beef
的tweet也会匹配。相关问题 更多 >
编程相关推荐