Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Get Twitter Trends in tweepy, and parse JSON

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.

like image 319
CryptoCo Avatar asked Jan 18 '14 11:01

CryptoCo


People also ask

How do you get the trending tweet in Python?

The get_place_trends() method of the API class in Tweepy module is used to fetch the top 50 trending topics for a specific location.

How do you get trending data on Twitter?

On Twitter's mobile apps, you can find Trends listed under the Trends section of the Explore tab when signed in to twitter.com on a desktop or laptop computer, Trends are listed in many places, including the Home timeline, Notifications, search results, and profile pages.


1 Answers

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
like image 73
senshin Avatar answered Sep 18 '22 18:09

senshin