2017-10-10 40 views
-1

脚本语言:Python的3.6Python书籍典型的错误: “字符串incides必须是整数”

参考教材:Python的数据可视化食谱[Milovanovic的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()顺便说一句,在哪里设置()是从哪里来的?]

请点我在正确的方向

+2

来自json_obj: 你好,那里有陌生人。如果你正在阅读这篇文章,那么你可能几年前没有看到我们的博客文章宣布这个API会消失:http://git.io/17AROg不要担心,你应该能够得到你需要的东西从闪亮的新事件API而不是。 –

回答

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([1,2,3,4,4,5,5,6,6]) 
{1, 2, 3, 4, 5, 6} 

注意,一组是无序的,所以不依赖于被排序的项目,因为他们似乎是在例子。

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()和的数据容器。集类似,他们店数量的对象名单。最大的区别是:

  • 组进行排序(如字典)
  • 集只包含独特的项目

您可以找到python的文档中的详细信息: https://docs.python.org/3/tutorial/datastructures.html#sets

我希望这有助于你的学习带来好运。

1

只要你得到一些问题的答案...

TypeError: string indices must be integers是因为,由于API下跌,entry现在只有一个字符串(u'documentation_url'),当entry['repository']它提出了一个错误,因为,用绳子,你只能get第n次从一个整数n(你不能得到仓库个字符)字符

[作为回购顺便说一句,在哪里设置()=组()是从哪里来的?]

当你做repos = set()你只是创建一个空集的对象其分配给repos。您将在稍后填写它repos.add(entry['repository']['url'])

1

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

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

你可以阅读更多有关集()数据结构在这里:https://docs.python.org/3/tutorial/datastructures.html

相关问题