JSON 或 SimpleJSON 和 Python 与 Twython

标签 json python-2.7 simplejson twython

我也是 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

我对 json.dumpsjson.loads 很困惑 - 我应该使用 json 还是 simplejson?

最佳答案

您不需要使用 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)

这将使您更容易找出可以循环的内容等。

关于JSON 或 SimpleJSON 和 Python 与 Twython,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16761526/

相关文章:

python - 改变读取文件的方向?

python - Google App Engine Python simplejson 转义?

python - simplejson 返回值不按顺序

python - 如何向管理表单添加自定义功能?

python - 如何解释这种随机的 python 行为?

c# - 在 C# 中将字符串转换为 JSON

javascript - jquery复制json对象

javascript - 如何通过 JavaScript 在 JSON 中构建此 XML 结构?

jquery - IE 尝试解析 JSON 时出错

java - 在 Android 中使用 Retrofit 时带有动态键的 JSON