nltk.twitter.twitter_demo module

Examples to demo the twitterclient code.

These demo functions should all run, with the following caveats:

  • You must have obtained API keys from Twitter, and installed them according to the instructions in the twitter HOWTO.

  • If you are on a slow network, some of the calls to the Twitter API may timeout.

  • If you are being rate limited while searching, you will receive a 420 error response.

  • Your terminal window / console must be able to display UTF-8 encoded characters.

For documentation about the Twitter APIs, see The Streaming APIs Overview and The REST APIs Overview.

For error codes see Twitter’s Error Codes and Responses <>

nltk.twitter.twitter_demo.ALL = [<function twitterclass_demo>, <function sampletoscreen_demo>, <function tracktoscreen_demo>, <function search_demo>, <function tweets_by_user_demo>, <function lookup_by_userid_demo>, <function followtoscreen_demo>, <function streamtofile_demo>, <function limit_by_time_demo>, <function corpusreader_demo>, <function expand_tweetids_demo>]

Select demo functions to run. E.g. replace the following line with “DEMOS = ALL[8:]” to execute only the final three demos.


Use TwitterCorpusReader tp read a file of tweets, and print out

  • some full tweets in JSON format;

  • some raw strings from the tweets (i.e., the value of the text field); and

  • the result of tokenising the raw strings.


Given a file object containing a list of Tweet IDs, fetch the corresponding full Tweets, if available.


Using the Streaming API, select just the tweets from a specified list of userIDs.

This is will only give results in a reasonable time if the users in question produce a high volume of tweets, and may even so show some delay.


Query the REST API for Tweets about NLTK since yesterday and send the output to terminal.

This example makes the assumption that there are sufficient Tweets since yesterday for the date to be an effective cut-off.


Use the REST API to convert a userID to a screen name.


Sample from the Streaming API and send output to terminal.


Use the REST API to search for past tweets containing a given keyword.


Initialize global variables for the demos.


Write 20 tweets sampled from the public Streaming API to a file.

nltk.twitter.twitter_demo.tracktoscreen_demo(track='taylor swift', limit=10)[source]

Track keywords from the public Streaming API and send output to terminal.

nltk.twitter.twitter_demo.tweets_by_user_demo(user='NLTK_org', count=200)[source]

Use the REST API to search for past tweets by a given user.


Use the simplified Twitter class to write some tweets to a file.


Decorator for demo functions


Get yesterday’s datetime as a 5-tuple.