【问题标题】:Parsing tweets from Twitter timeline using Python3.4: requests, Json and dictionaries使用 Python3.4 从 Twitter 时间线解析推文:请求、Json 和字典
【发布时间】:2014-05-14 00:16:32
【问题描述】:

我的第一个问题 :) 我正在学习将 api 与 python 一起使用,所以我正在从 twitter 中提取我的时间线推文。 我成功地将数据提取到字典中,但结果格式与我的第一个项目不同(不同的 api),所以我无法确定使用什么元素来迭代推文。

import requests
import json
from requests_oauthlib import OAuth1


url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?_count=3&screen_name=dimbodoyle&count=2'
auth = OAuth1('auth supplied'))

requests.get(url, auth=auth, verify=False)
response = requests.get(url, auth=auth, verify=False)
data = response.json()


# This is where the problems start
output = ''
for n in data:
    print(n)
    output += ['data'][n]['text'] + '\n'

with open('testTwitter.txt', mode='w', encoding='utf-8') as f:
    f.write(output)

print('Done')

当我在 python 中运行时,我收到以下错误 回溯(最近一次通话最后): 文件“C:\Python34\twitter\Connecting to twitter with request and json.py”,第 17 行,在 输出 += ['data'][n]['text'] + '\n' TypeError:列表索引必须是整数,而不是字典。

有人有什么想法吗?我知道它想要一个整数用于循环,我在这种情况下得到的 n 似乎是整个字典,但我不知道为什么,也不知道如何更正它。

非常感谢任何帮助

【问题讨论】:

    标签: python json twitter dictionary


    【解决方案1】:

    n 是一个包含状态而不是其索引的字典,因此您可以改为使用n["text"]

    statuses = response.json()
    print "\n".join([status["text"] for status in statuses])
    

    【讨论】:

    • 作者可能更喜欢output = "\n".join([status["text"] for status in statuses]),而不是print "\n".join([status["text"] for status in statuses]),因为他们计划稍后使用它来写入文件。
    • 感谢您的帮助,所以我必须挂钩字典中的一个元素来解析它?
    • 实际上你们中的任何一个都知道如何以我在原始代码中的循环的形式来做到这一点吗?这对我来说是最容易理解的解决方案......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 2014-05-04
    • 1970-01-01
    相关资源
    最近更新 更多