Python:以tweepy获取Twitter趋势,并解析JSON

时间:2014-01-18 11:08:59

标签: python json twitter tweepy

好的,请注意这是我的第一篇文章

所以,我正在尝试使用Python来获取Twitter趋势,我正在使用python 2.7和Tweepy。

我想要这样的东西(有效):

#!/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

它提供了一个巨大的JSON字符串,

我想将每个趋势名称提取为变量,理想情况下为字符串格式str(trendsname)

理想情况下,哪个趋势的名称会如此:     trendsname = str(trend1) + " " +str(trend2) + " " 等等,对于每个趋势名称。

请注意我只学习Python。

2 个答案:

答案 0 :(得分:7)

看起来Tweepy会为您反序列化JSON。因此,trends1只是一个普通的Python列表。在这种情况下,您可以简单地执行以下操作:

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)

结果:

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

答案 1 :(得分:5)

我认为以下代码也可以正常运行:

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