【问题标题】:Logical Operators in Tweepy FilterTweepy 过滤器中的逻辑运算符
【发布时间】: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 都很陌生。 thisthis 看起来都是相似的查询,但它们与同时跟踪多个术语有关,而不是跟踪包含术语的推文子集。我在tweepy documentation 中找不到任何内容。

我知道另一种选择是跟踪所有包含“taco”的推文,然后通过“chicken”或“beef”过滤到我的数据库中,但我担心如果我做一个一般的流式传输速率限制会遇到 1%搜索然后在 Python 中对其进行过滤,因此我更喜欢首先从 Twitter 流式传输我想要的术语。

提前致谢-

山姆

【问题讨论】:

    标签: python filter tweepy


    【解决方案1】:

    Twitter 不允许您非常精确地匹配关键字。但是,track parameter documentation 声明关键字中的空格等同于逻辑 ANDS。您指定的所有术语都是 OR'd 在一起的。

    因此,要实现您的 "taco" AND ("chicken" OR "beef") 示例,您可以尝试使用参数 [taco chicken, taco beef]。这将匹配包含单词tacochickentacobeef 的推文。然而,这并不是一个完美的解决方案,因为包含tacochickenbeef 的推文也会被匹配。

    【讨论】:

    • 谢谢@Aaron-这会很好用。顺便说一句,您是否知道是否有一种方法可以返回以字符序列开头的所有单词?例如,在 R 中,如果我想返回“plant”、“planting”和“planted”,则可以查询“plant+”。
    • 我不这么认为,抱歉。就像我在回答中所说的那样,API 在允许您进行过滤方面非常粗略。
    • @AaronHill 例如,要过滤hellobye这两个词(逻辑或),我们应该使用track=['hello,bye']或使用track=['hello', 'bye']或者可能没有区别?
    猜你喜欢
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    相关资源
    最近更新 更多