【问题标题】:Python: Get Twitter Trends in tweepy, and parse JSONPython:在 tweepy 中获取 Twitter 趋势,并解析 JSON
【发布时间】:2014-02-07 19:23:54
【问题描述】:

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

所以,我正在尝试使用 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 是的,我知道它,但不确定如何使用它。
  • 好的,既然如此,就把trends1的内容贴出来吧。如果它太大而无法放在这里,请将其粘贴在 pastie 中。
  • @senshin 好的:pastie.org/8644855 我想我想提取“u'name': u'#PolandNeedsWWATour',”值,例如,只拥有“#PolandNeedsWWATour”,然后为每个名称执行此操作趋势,如果这有意义的话

标签: python json twitter tweepy


【解决方案1】:

看起来 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 字符串的源吗?我会假设的。
  • @RPiPasswordGen 你应该设置trends1 = api.trends_place(1) 就像你在你的问题中一样。你问的是这个吗? (我刚刚将其编辑到我的答案中)
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2021-03-08
    • 2013-04-12
    • 2017-02-11
    • 1970-01-01
    • 2023-04-01
    • 2011-06-12
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    相关资源
    最近更新 更多