jtlaurente
jtlaurente

Reputation: 43

How to narrow down search results in Tweepy?

Currently, I'm searching for tweets like this:

public_tweets = api.search("what do we do?", count=10, result_type="recent")
for tweet in public_tweets:
    tweet_text = tweet.text
    print(tweet_text)

However, when printing the results, it returns all the tweets that include that phrase in any order. It doesn't matter if there are words in between or anything. How can I change this so that I find tweets containing ONLY this phrase?

Upvotes: 4

Views: 80

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169444

According to my research there is no way to specify an exact match, say via regular expression to the Twitter API.

However, you can post-process the tweets you get back using regular expressions:

import re, tweepy

def twitter():
    auth = tweepy.OAuthHandler("", "")
    auth.set_access_token("","")

    api = tweepy.API(auth, wait_on_rate_limit=True,
                     wait_on_rate_limit_notify=True)

    public_tweets = api.search("what do we do?", count=100, result_type="recent")
    for tweet in public_tweets:
        tweet_text = tweet.text
        if re.search(r"[Ww]hat do we do\?",tweet_text):
            print(tweet_text)

if __name__ == '__main__':
    twitter()

Result just now:

RT @traceyfutures: This is disappointing. She really was our best hope. What do we do now?
RT @oochqmemes: tsukki: (is unconscious)
yama: tsukki's not breathing! what do we do?!
kuroo: i'll give him mouth to mouth
tsukki: (wakes u…

Upvotes: 4

Related Questions