python - 我是编码新手,在将数据导入 python 时遇到问题

标签 python function error-handling

我从 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 问题一样,最好的起点通常是文档。 This is the API endpoint in question. 考虑到这一点,我们可以看到响应的预期结构。

有了你的代码,你就快到了。您需要进一步检查响应结构。 “departures”是一个字典,它以行号作为键(例如“1”)而不是单词“line”。牢记这一点,将打印语句更改为如下所示:

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

关于python - 我是编码新手,在将数据导入 python 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58495926/

相关文章:

javascript 调用函数作为数组元素

python - Python 对象实例是该语言中唯一的对象吗?

Python 正则表达式

javascript - 让递归函数永远运行?

excel - 捕获连接错误

asp.net-mvc-4 - 如何错误处理NullReferenceException

php - 从Symfony2捕获ContextErrorException

python - 如何将数据框/列表写入 csv 文件?

python - cairocffi - DLL 找不到入口点 inflateReset2

c - 是否可以强制函数参数在 C 中保持不变?