Python: Get Twitter twitter in tweepy and parse JSON

Ok, so please note that this is my first post

So, I am trying to use Python to get Twitter Twitter, 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 

This gives a massive JSON string,

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

What would ideally have the names of such trends: trendsname = str(trend1) + " " +str(trend2) + " " , etc. for each of the trend names.

Please note that I only study Python.

+6
source share
2 answers

It looks like Tweepy is deserializing JSON for you. So trends1 is just a regular Python list. In this 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 
+7
source

I think the following code works fine:

 trends1 = api.trends_place(1) trends = set([trend['name'] for trend in trends1[0]['trends']]) print trends 
+4
source

All Articles