Search code examples
pythontwitterdata-analysis

How can filter for specific keywords in extracted tweets?


I have a code that gives me the tweets from my timeline on Twitter and saves them to a CSV. How can I make it search and save only tweets that contain a specific keyword X?

The code is below:

access_token = config['twitter']['access_token']
access_token_secret = config['twitter']['access_token_secret']

auth = tweepy.OAuthHandler(api_key, api_key_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

public_tweets = api.home_timeline()
data = []

for tweet in public_tweets:
    data.append([tweet.created_at, tweet.user.screen_name, tweet.text])

Solution

  • Python provides the in operator for words in strings, so you don't have to use regex or something more involved than a simple if, as per the following:

    query_string = "word" # your keyword
    
    for tweet in public_tweets:
        if query_string in tweet.text:
            data.append([tweet.created_at, tweet.user.screen_name, tweet.text])