簡體   English   中英

我是編碼新手,無法將數據導入 python

[英]I'm new to coding and am having trouble with importing data into python

我從 API 導入數據,需要幫助來獲取一組特定的數據。 每當我嘗試打印一組特定的數據並測試運行代碼時,我都會收到一條 KeyError 消息,並且想知道如何修復它。

到目前為止,我已經嘗試了 print("這是前往 " + resp['departures']['line']['direction'] 的公交線路 1 的當前預期出發時間),但它仍然不起作用。

from urllib.request import urlopen
import json 

def askbot(bus_stop):

    if bus_stop == "CU2":
        url =  urlopen("https://transportapi.com/v3/uk/bus/stop/43001053801/live.json? [app_id]&[app_key]&group=route&nextbuses=yes")
        data = json.loads(url.read().decode())
        json_str=json.dumps(data)
        resp=json.loads(json_str)  
        which_line = input("Which bus line would you like to know? ")
        if which_line == "1":
           print("Here is the current expected departure time for bus line  1 heading to " + resp['departures']['line']['direction'])
        else:
            print("That is not a valid line!")
    else:
        print("That bus stop does not exist!")

which_stop = input("Which bus stop timetable would you like to know? ")
askbot(which_stop)

這段代碼目前只是測試這個特定的公交車站,但是,當為第二個輸入輸入“1”時,會出現一條錯誤消息說

File "c:/Users/[Name]/Desktop/[Folder]/Test 2.py", line 23, in <module>
askbot(which_stop)
  File "c:/Users/[Name]/Desktop/[Folder]/Test 2.py", line 14, in askbot
print("Here is the current expected departure time for bus line 1 heading to " + resp['departures']['line']['direction'])
KeyError: 'line' 

我不確定這意味着什么,我還要注意 API 實時更新,信息可能會發生變化。

與大多數 API 問題一樣,最好的起點通常是文檔。 這是有問題的 API 端點。 考慮到這一點,我們可以看到響應的預期結構。

使用您的代碼,您就快到了。 您需要進一步檢查響應結構。 “departures”是一個字典,它以行號作為鍵(例如“1”)而不是單詞“line”。 牢記這一點,將打印語句更改為如下所示:

print("Here is the current expected departure time for bus line  1 heading to " + resp['departures'][which_line]['direction'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM