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

Cry*_*oCo 7 python twitter json 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
Run Code Online (Sandbox Code Playgroud)

这给了一个巨大的JSON字符串,

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

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

请注意我只学习Python.

sen*_*hin 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)
Run Code Online (Sandbox Code Playgroud)

结果:

#PolandNeedsWWATour #DownloadElyarFox #DünMürteciBugünHa?ha?i #Galatasarayl?l?kNedir #KnowTheTruth Tameni Video Anisa Rahma Mikaeel Manado JDT
Run Code Online (Sandbox Code Playgroud)


Abh*_*rma 6

我认为以下代码也可以正常工作:

trends1 = api.trends_place(1)
trends = set([trend['name'] for trend in trends1[0]['trends']])
print trends 
Run Code Online (Sandbox Code Playgroud)