2014-01-18 48 views
6

好了,请注意,这是我的第一篇文章的Python:获取Twitter的趋势tweepy,并解析JSON

所以,我试图用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。

+0

你知道的内置的在'json'模块及其''json.loads()'函数中? – senshin

+0

@ senshin是的,我意识到这一点,但我不确定如何使用它。 – CryptoCo

+0

好的,在这种情况下,发布'trends1'的内容。如果它太大而不适合放在这里,请将它粘贴在[pastie](http://pastie.org)中。 – senshin

回答

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 
+0

非常感谢!我会投票,但它说我需要15点声望。 **忽略以下语句,它的工作原理!**我可以将trends1设置为JSON字符串的来源吗?我会这样认为的。 – CryptoCo

+0

@RPiPasswordGen你应该像你在你的问题中设置'trends1 = api.trends_place(1)'。你在问什么? (我刚刚编辑了我的答案) – senshin

4

我认为下面的代码工作太细:

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