编程语言
首页 > 编程语言> > python – Twitter API:如何在使用Twython搜索推文时排除转推

python – Twitter API:如何在使用Twython搜索推文时排除转推

作者:互联网

我试图在我的Twython搜索中排除转推和回复.

这是我的代码:

from twython import Twython, TwythonError

app_key = "xxxx"
app_secret = "xxxx"
oauth_token = "xxxx"
oauth_token_secret = "xxxx"   

naughty_words = [" -RT"]
good_words = ["search phrase", "another search phrase"]
filter = " OR ".join(good_words)
blacklist = " -".join(naughty_words)
keywords = filter + blacklist

twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret) 
search_results = twitter.search(q=keywords, count=100)

问题是-RT功能并没有真正起作用.

编辑:

我已经尝试了@forge建议,虽然它打印了如果推文不是转推或回复,当我将它们合并到下面的代码中时,机器人仍然会发现推文,转推,引用和回复.

twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret) query = 'beer OR wine AND -filter:retweets AND -filter:replies' 
response = twitter.search(q=query, count=100) 
statuses = response['statuses'] 
try: 
for tweet in statuses: 
try: 
twitter.retweet(id = tweet["id_str"]) 
except TwythonError as e: 
print e 
except TwythonError as e: 
print e

有任何想法吗?是否有过滤器:报价?

解决方法:

正确的语法是-filter:retweets.

如果您要搜索“搜索词组”或“其他搜索词组”并排除转推,则查询应为:

query = "search_phrase OR another_search_phrase -filter:retweets"

要排除回复,请添加-filter:回复如下:

query = "search_phrase OR another_search_phrase -filter:retweets AND -filter:replies"

这应该有效,您可以通过检查in_reply_to_status_id和retweeted_status中的状态字段来验证它:

>如果in_reply_to_status_id为空,则状态不是回复
>如果没有转发字段retweeted_status,则状态不是转发

随着Twython:

import twython

twitter = twython.Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) 

query = 'wine OR beer -filter:retweets AND -filter:replies' 
response = twitter.search(q=query, count=100)
statuses = response['statuses']
for status in statuses:
    print status['in_reply_to_status_id'], status.has_key('retweeted_status')

# Output should be (None, False) to any status

标签:python,twitter,twython
来源: https://codeday.me/bug/20190724/1525615.html