2017-10-10 37 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

相關問題