Step 1 – Install Python Packages

Json is already implemented in Python >=2.7 and python-twitter installs all the appropriate packages. After that, you are ready to start!

Step 2 – Make a Twitter app

This is an easy step and I am going to walk you through it. First go here and log in to your twitter account. This is the development site of twitter, where you can build your own apps!

Click on the button “Create new app” at the top right corner. Fill in the blanks with your information and then click on “Create your Twitter application”. Here is an example.

After you have created your app, you will be redirected to the App’s homepage. Go to Keys and Access Tokens and click on “Create My Access Token” at the bottom of the page. At the top of your page, you can find your secret keys and at the bottom your access tokens. Here is an example.

Write down those keys and remember, those keys are secret! DO NOT SHARE! After that you need to adjust your app’s access level, just to avoid further validation (if you are going to use it for your own account you do not need to change this). Go to Permissions->Select “Read Only”->Update Settings. That’s it! Now we can now write code.

Step 3 – Get the Tweets

First of all, we want to import the appropriate packages.

import twitter
import json

Json is needed because the twitter API returns us the tweet in json format. For example:

As you can see I created a class because I am using this sampling a lot in my research, I suggest you do the same. When I am going to create my class object, I will parse the API keys. Next, in the SampleTwitter class, I created a method called getTweets() where I gave as input the account I want to sample. BE CAREFUL, there is a limit on how many tweets per day you can retrieve!

As you can see at line 15 and 16 I extract the tweet’s text from the json format. Also, I want to talk about the GetUserTimeline’s parameter at line 7. Here I sampled the last 200 tweets, without replies, without retweets and with the user handles. You can find all the parameters here.

Conclusion

This is it! You can now sample twitter account, harvest tweets and process the results. Be careful tho, as I said before, there is a limit on how many tweets you can retrieve! Anyways, until next time, take care and have fun!