我从API导入了数据,需要帮助来获取一组特定的数据。每当我尝试打印一组特定的数据并测试代码时,我都会收到KeyError消息,并想知道如何解决它。
到目前为止,我已经尝试过print(“这是公共汽车1号线目前前往“ + resp ['departures'] ['line'] ['direction']的预计出发时间),但仍然没有工作。
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会实时更新,并且信息可能会发生变化。
答案 0 :(得分:0)
与大多数API问题一样,最好的起点通常是文档。 This is the API endpoint in question. 考虑到这一点,我们可以看到预期的响应结构。
有了您的代码,您就快到了。您需要进一步检查响应结构。 “出发地”是一种以行号为键(例如“ 1”)而不是单词“ line”的字典。请牢记这一点,将print语句更改为如下所示:
x %>% dplyr::group_by(year) %>% dplyr::summarise(number = sum(number))