Twitter API: Extracting Tweets with Specific Phrase

Twitter has been a good source for Data Mining. Many data scientists and analytics companies collect tweets and analyze them to understand people’s opinion about some matters.

In this tutorial, you will learn how to use Twitter API and Python Tweepy library to search for a word or phrase and extract tweets that include it and print the results.

Note: This tutorial is different from our other Twitter API tutorial in that the current one uses Twitter Streaming API which fetches live tweets while the other tutorial uses the cursor method to search existing tweets. You can use the cursor to specify the language and tweet limit and you can also filter retweets using cursor.

First of all, you must install the Python Tweepy library.  You can do this by running:

Note that if you are on Mac or Linux, you might need to start with sudo  to avoid permissions issues.

Now you need to import the libraries you need. Add the following snippet:

Specify the phrase that you want to search.

Go to Twitter Developers page and create a new app. Once you have created an app, generate a new access token and its secret.

Enter your Consumer API keys, Access Token and Access Token Secret


Now you need to setup the streaming logic. This following code is what you need to listen for data from twitter’s streaming API.

Start tweet collection and filter tweets on basis of the given phrase.

Add authentication for twitter’s streaming API and the main function.

Call the API with the phrase defined earlier.


Full Project Code



Rating: 5.0/5. From 3 votes.
Please wait...

Leave a Reply