【问题标题】:JSON or SimpleJSON and Python with TwythonJSON 或 SimpleJSON 和 Python 与 Twython
【发布时间】:2013-05-21 14:56:30
【问题描述】:

我也是 Python 和 JSON 的新手。我安装了 twython 来与 Twitter API “对话”。我在 Mac 上使用 Python 2.7。

我想通过 API 获得我的提及。该程序应识别提到我的 Twitter 用户。

我试试:

t = Twython(...)
men = t.get_mentions_timeline()

用户被提及一次,print men 显示很多这样的东西:

[{u'contributors': None, u'truncated': False, u'text': .... u'Sun May 26 09:18:55 +0000 2013', u'in_reply_to_status_id_str': None, u'place': None}]

在这些东西的某个地方,我看到了我想从响应中提取的所有内容。

如何提取screen_name

我对@9​​87654324@ 或json.loads 感到很困惑——我应该使用json 还是simplejson

【问题讨论】:

  • 我已经找到了解决方案 - 只有一个用于: 男性提及: mu = 提及 ['user'] tweetid = 提及 ['id'] usern = mu['screen_name'] print tweetid打印用户

标签: json python-2.7 simplejson twython


【解决方案1】:

您不需要使用json(或simplejson,这是完全相同的库;它在与Python 捆绑时被重命名); Twython 库已经为您解码了 JSON 中的所有内容。

您从 API 中获得了一个列表,每个条目都是一个 dict;每个这样的字典都是一条推文。您可以查看Twitter API documentation 中包含的内容。循环遍历该列表;有些项目本身就是字典或列表:

for mention in men:
    print mention['user']['screen_name']
    if mention['contributors']:
        print [con['screen_name'] for con in mention['contributors']]

要找出完整的结构,请使用pprint.pprint() 打印结构化版本:

import pprint

pprint.pprint(men)

这将使您更容易弄清楚可以循环的内容等。

【讨论】:

  • 谢谢,但我收到一个错误:KeyError: 'screen_name' 也许我应该提到 screen_name 是实体的一部分 看起来像这样:u'entities': {u'symbols': [], u'user_mentions': [{u'id': 1457484992, u'indices': [0, 8], u'id_str': u'1457484992', u'screen_name': u'CyclopT', ....
  • @hildwin:我在之前的编辑中有一个错误;你能告诉我你用的是什么吗?使用pprint 技巧来确定什么是列表,什么是字典。
  • 第二个循环不起作用。结构是:`u'user': {u'screen_name': u'NAME'(更多内容)}`
  • @hildwin:是的,我正在使用contributors 键(在您的第一个示例中是None,所以这不起作用)。 user有一个screen_name 键。我指向的 API 链接包括 user 键的链接,指向 Users page。更新了答案以显示贡献者(如果有的话)。
猜你喜欢
  • 2010-10-17
  • 2011-03-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-11
  • 2011-01-02
  • 1970-01-01
  • 2012-09-01
  • 1970-01-01
相关资源
最近更新 更多