gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:44:11 25 4
gpt4 key购买 nike

我从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com