Python: Get Twitter Trends in tweepy, and parse JSON

CryptoCo picture CryptoCo · Jan 18, 2014 · Viewed 13.6k times · Source

Ok, so please note this is my first post

So, I am trying to use Python to get Twitter Trends, I am using python 2.7 and Tweepy.

I would like something like this (which works):

#!/usr/bin/python
# -*- coding: utf-8 -*-
import tweepy
consumer_key = 'secret'
consumer_secret = 'secret'
access_token = 'secret'
access_token_secret = 'secret'
# OAuth process, using the keys and tokens
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
trends1 = api.trends_place(1)

print trends1

That gives a massive JSON string,

I would like to extract each trend name to a variable, in string format str(trendsname) ideally.

Which would ideally have the names of trends like so: trendsname = str(trend1) + " " +str(trend2) + " " and so on, for each of the trend names.

Please note I am only learning Python.

Answer

senshin picture senshin · Jan 18, 2014

It looks like Tweepy deserializes the JSON for you. As such, trends1 is just an ordinary Python list. This being the case, you can simply do the following:

trends1 = api.trends_place(1) # from the end of your code
# trends1 is a list with only one element in it, which is a 
# dict which we'll put in data.
data = trends1[0] 
# grab the trends
trends = data['trends']
# grab the name from each trend
names = [trend['name'] for trend in trends]
# put all the names together with a ' ' separating them
trendsName = ' '.join(names)
print(trendsName)

Result:

#PolandNeedsWWATour #DownloadElyarFox #DünMürteciBugünHaşhaşi #GalatasaraylılıkNedir #KnowTheTruth Tameni Video Anisa Rahma Mikaeel Manado JDT