Python书籍示例错误:“string incides必须是整数”

时间:2017-10-10 18:08:03

标签: python typeerror

脚本语言:Python 3.6

参考书:Python数据可视化手册[Milovanović2013-11-25]

自学Python数据可视化

当我从书中执行代码时

import requests

url = 'https://github.com/timeline.json'

r = requests.get(url)
json_obj = r.json()

repos = set() # we want just unique urls
for entry in json_obj:
    try:
        repos.add(entry['repository']['url'])
    except KeyError as e:
        print ("No key %s. Skipping..." % (e))

from pprint import pprint 
pprint(repos)

我收到错误

repos.add(entry['repository']['url'])
TypeError: string indices must be integers

如何排除故障?当我看到similar threads时,我画了一个空白

书中的代码是否正确?

[顺便说一句,repos = set()中的set()来自哪里?]

请指出正确的方向

4 个答案:

答案 0 :(得分:2)

如果你打印json_obj,你会得到这个:

{'message': 'Hello there, wayfaring stranger. If you’re reading this then you pr
obably didn’t see our blog post a couple of years back announcing that this API 
would go away: http://git.io/17AROg Fear not, you should be able to get what you
 need from the shiny new Events API instead.', 'documentation_url': 'https://dev
eloper.github.com/v3/activity/events/#list-public-events'}

所以这个链接看起来很旧,你必须看看新的链接。

对于你的第二个问题: set()是一个类似于dict()list()的数据容器。集合类似于列表,因为它们存储了许多对象。最大的区别是:

  • 集合未排序(如字典)
  • 只包含唯一商品

您可以在python文档中找到更多信息: https://docs.python.org/3/tutorial/datastructures.html#sets

我希望这会有所帮助,祝你学习顺利。

答案 1 :(得分:1)

这样你就能得到一些问题的答案......

TypeError: string indices must be integers是因为,由于API已关闭,entry现在只是一个字符串(u'documentation_url'),而entry['repository']时会引发错误,因为字符串,你只能get来自整数n 的第n个字符(你无法获得存储库字符)。

[另外,repos = set()中的set()来自哪里?]

执行repos = set()时,您只创建一个空集对象,并将其分配给repos。您可以稍后使用repos.add(entry['repository']['url'])

填写它

答案 2 :(得分:1)

您尝试访问的entry对象是一个字符串,因此您无法使用非整数索引访问它。我尝试运行你的代码,由于请求太多,网址似乎被关闭或阻止,所以这可能是entry最终成为字符串对象的原因。

repos = set()意味着,当您向repos添加新网址时,它会忽略该网址已在该网址中的情况,因此您不会重复这些网址。如果您使用repos = [],则必须在每次插入时手动检查重复项(除非您想允许重复项)。

您可以在此处详细了解set()数据结构:https://docs.python.org/3/tutorial/datastructures.html

答案 3 :(得分:1)

正在使用的API已过时。以下代码使用当前API:

import requests
url = 'https://api.github.com/events' # New API URL

r = requests.get(url)
json_obj = r.json()

repos = set() # we want just unique urls
for entry in json_obj:
    try:
        repos.add(entry['repo']['url'])  # Key change. 'repo' not 'repository'
    except KeyError as e:
        print ("No key %s. Skipping..." % (e))

from pprint import pprint 
pprint(repos)

正如其他人所指出的,set()创建了一个只能包含唯一值的set对象。例如:

>>> set([1,2,3,4,4,5,5,6,6])
{1, 2, 3, 4, 5, 6}

请注意,集合是无序的,因此不要依赖于正在排序的项目,因为它们似乎在示例中。