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

5

我想在Twython搜索中排除转推(retweets)回复(replies)

这是我的代码:

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:quotes的过滤器?

2
我已经尝试在我的坏词字段中包含“-filter:retweets”和“-filter:replies”,但没有任何运气。难道仅仅让api返回推文而不是回复、引用或转推真的这么困难吗? - B. Chas
你也可以使用[Craig Addyman]提供的教程 - http://www.craigaddyman.com/mining-all-tweets-with-python/ - Dinesh
1个回答

11

正确的语法是-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字段,则状态不是转推

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

1
太棒了!此外,如果有人需要各种过滤器的API文档,请访问:https://developer.twitter.com/en/docs/tweets/rules-and-filtering/overview/standard-operators - jtubre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接