One of main applications for Twitter’s content analysis is about watching trending topics, specially because of the microblog’s quality: users are more likely to spread opinions about specific subjects, brands and personalities. That quality provides a good framework for sentiment analysis about those terms and assists the decision-making (in an advertising campaign, for example).
In a previous post, I showed how to implement a tweet collector in Python using Tweepy. To obtain the current network trending topics, the initial steps for Tweepy setup and Twitter application registering are the same. In this case, the additional argument you’ll need to run the code is the WOE (Where On Earth) ID, which sets the location from where the topics will be retrievied. You can obtain the WOE ID for a specific location on http://woeid.rosselliot.co.nz/. For world trending topics, the default WOE ID value is 1.
THE SOURCE CODE
# -*- coding: utf-8 -*-
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
api = tweepy.API(auth)
# Where On Earth ID for Brazil is 23424768.
BRAZIL_WOE_ID = 23424768
brazil_trends = api.trends_place(BRAZIL_WOE_ID)
trends = json.loads(json.dumps(brazil_trends, indent=1))
for trend in trends["trends"]:
If you’re already familiar with Tweepy library, the code above may be easy to understand. The method trends_place returns a set of objects with information about the topics in JSON format, so I used the dump method from JSON standard library to parse the data. In this example, the algorithm only prints the title of the topic, only to show how to manipulate the object. One of the benefits from using the API’s method is the amount of topics retrieved are significantly greater than the web platform (that shows only 10 topics at a time). If you have any doubts or suggestions, please use the comment area or contact me.