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

7

注意,这是我的第一篇帖子。

我正在尝试使用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。


你是否了解内置的 json 模块及其 json.loads() 函数? - senshin
@senshin 是的,我知道它,但不确定如何使用它。 - CryptoCo
好的,那么请发布“trends1”的内容。如果太大无法放在这里,请将其粘贴到pastie中。 - senshin
@senshin 好的:http://pastie.org/8644855 我认为我想要提取"u'name': u'#PolandNeedsWWATour',"的值,例如,只需将"#PolandNeedsWWATour"单独提取出来,并对每个趋势名称执行此操作,如果有意义的话。 - CryptoCo
请注意,Tweepy 4.0版本已将“trends_place”方法重命名为“get_place_trends”。 - ezzeddin
2个回答

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

非常感谢!我想要点赞,但它说我需要15个声望。忽略以下声明,它有效!我能将trends1设置为JSON字符串的来源吗?我会假设可以。 - CryptoCo
@RPiPasswordGen 你应该像你在问题中所提到的那样设置trends1 = api.trends_place(1)。这是你在问什么吗?(我刚刚编辑了我的答案) - senshin

6
我认为以下代码也可以正常工作:
trends1 = api.trends_place(1)
trends = set([trend['name'] for trend in trends1[0]['trends']])
print trends 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接