Twitter API:如何在使用Twython搜索tweets时排除转发

2024-05-15 10:09:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我的搜索中排除retweetsreplies

这是我的代码:

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 suggestion,虽然它确实打印了if tweets不是转发或回复,但当我将它们合并到下面的代码中时,bot仍然会找到tweets、转发、引用和回复。

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:quotes吗?


Tags: keytokenappsearchsecrettwitterfilteroauth
1条回答
网友
1楼 · 发布于 2024-05-15 10:09:26

正确的语法是-filter:retweets

如果要搜索词条"search phrase""another search phrase"并排除转发,则query应为:

query = "search_phrase OR another_search_phrase -filter:retweets"

要同时排除答复,请按如下方式添加-filter:replies

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

这应该可以工作,您可以通过检查状态字段in_reply_to_status_idretweeted_status来验证它:

  • 如果in_reply_to_status_id为空,则状态不是答复
  • 如果没有字段retweeted_status,则Status不是retweet

使用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

相关问题 更多 >