Tweepy 检查推文是否是转推

Nat*_*val 6 python twitter tweepy

我开始在 Python 中使用 Tweepy 3.6.0,但我有一些问题。

首先,我想获取推文列表(使用 api.search 方法),但不是转推。我觉得有些奇怪。尝试使用他的 ID 和 author_name 访问推文。它会自动重定向到原始推文(不同的 ID 和 author_name)。

经过一番搜索,我发现人们在谈论“retweeted_status”键。如果键退出,那么它是一个RT。但在我下面的示例中,我的 Tweet 对象中没有 retweeted_status,但重定向到原始 Tweet 在这里。

我理解错了吗?

谢谢

Tra*_*ley 11

您可以选择仅搜索转推或从搜索查询中排除所有转推。

用于搜索无转发“-filter:retweets”

for tweet in tweepy.Cursor(api.search, q='github -filter:retweets',tweet_mode='extended').items(5):
Run Code Online (Sandbox Code Playgroud)

仅搜索转推“过滤器:转推”

 for tweet in tweepy.Cursor(api.search, q='github filter:retweets',tweet_mode='extended').items(5):
Run Code Online (Sandbox Code Playgroud)

额外的信息:

虽然您可以直接在搜索查询中排除转推,但也很容易找到推文是否是转推,因为所有转推都以“rt @UsernameOfAuthor”开头。您可以通过执行基本的 if 语句来查看推文是否以 rt 开头,从而确定推文是否为转推。

首先进行基本查询并将信息保存到变量中。

for tweet in tweepy.Cursor(api.search, q='github',tweet_mode='extended').items(5):
    # Defining Tweets Creators Name
    tweettext = str( tweet.full_text.lower().encode('ascii',errors='ignore')) #encoding to get rid of characters that may not be able to be displayed
    # Defining Tweets Id
    tweetid = tweet.id
Run Code Online (Sandbox Code Playgroud)

然后打印信息用于演示目的

    # printing the text of the tweet
    print('tweet text: '+str(tweettext))
    # printing the id of the tweet
    print('tweet id: '+str(tweetid))
Run Code Online (Sandbox Code Playgroud)

然后是 if 语句来判断它是否是转推

# checking if the tweet is a retweet (this method is basic but it will work)
if tweettext.startswith("rt @") == True:
    print('This tweet is a retweet')
else:
    print('This tweet is not retweet')
Run Code Online (Sandbox Code Playgroud)

  • 这是真的啊啊。我找到了另一种方法:“isRT = hasattr(tweet, 'retweeted_status')” (2认同)
  • 有多种方法可以判断一条推文是否为转发,我给出了我更喜欢使用的方法。您可以检查的另一种方法甚至只是检查推文是否包含名为“retweeted_status”的属性。剥猫皮的方法有很多种:) (2认同)