我有Tweepy的json输出,我现在正尝试解析它。例如,某些输出是特定区域的趋势主题标签。由于输出量很大,因此我试图确定如何有效地解析所有主题标签。 json输出中还有其他信息,例如userid
,countrycode
等。但是,我只对例如列为name: '#gamenight
的主题标签感兴趣。
# using Tweepy
api.trends_place(2295420)
import json
# Here is a portion of the Tweepy output I received
trends = [{'trends': [{'name': '#RCBvKKR', 'url': 'http://twitter.com/search?q=%23RCBvKKR', 'promoted_content': None, 'query': '%23RCBvKKR', 'tweet_volume': 101508}, {'name': 'created_at': '2019-04-06T00:07:14Z', 'locations': [{'name': 'Bangalore', 'woeid': 2295420}]}]
hashtags = json.dumps(trends)
# Am trying to end up with a way of just extracting 'name' which I believe is how the hashtags are captured
print(hashtags['name'])
答案 0 :(得分:0)
接收hastags["trends"][0]["name"]
应该是#RCBvKKR
好的,我修复了它。首先,发布的代码令人困惑。您发布的json无效(括号缺失,名称键没有值)。其次,使用命令json.dumps(trends)
,您将已经有效的python字典转换为字符串,该字符串是数组,因此错误(string indices must be integers
)
固定版本如下:
import json
trends = [{'trends': [{'name': '#RCBvKKR', 'url': 'http://twitter.com/search?q=%23RCBvKKR', 'promoted_content': None, 'query': '%23RCBvKKR', 'tweet_volume': 101508}, {'name':"This was missing", 'created_at': '2019-04-06T00:07:14Z', 'locations': [{'name': 'Bangalore', 'woeid': 2295420}]}]}]
print(trends[0]["trends"][0]["name"])
现在输出为#RCBvKKR
如果您确实从API接收到json字符串,请使用json.parse(response)
将字符串转换为python dict。