以下是源码:
import json
from urllib import request
OD=open('od_walking.txt').read().splitlines()
url_base='https://restapi.amap.com/v5/direction/bicycling?parameters&key=47e4ca6d9cd2c2e62b9e300dcd1a8370&origin={0},{1}&destination={2},{3}'
output=open('one_wsy.txt','wb')
for i in OD:
x1,y1,x2,y2=i.split('\t')
url=url_base.format(x1,y1,x2,y2)
try:
html=request.urlopen(url,timeout=15).read()
js=json.loads(html)
d=js['route']['paths'][0]['distance']
c=js['route']['paths'][0]['cost']['duration']
out='{0}\t{1}\n'.format(d,c)
output.write(out.encode('utf8'))
except Exception as e:
print(repr(e))
output.write(url.encode('utf8'))
output.close()
报错显示不存在cost这个键,你可以看下js['route']['paths'][0]
你在使用高德地图API获取数据时遇到了KeyError,这通常是由于尝试访问的字典键不存在于字典中根据你提供的代码,你正在尝试从返回的JSON数据中获取某些值,尤其是'route'
和'paths'
下的'distance'
和'cost'
然而,如果这些键在返回的JSON数据中不存在,就会引发KeyError
以下是可能的解决方案:
get()
方法来实现这一点这个方法允许你为不存在的键提供一个默认值,这样就不会因为尝试访问不存在的键而抛出KeyError例如,你可以这样改写你的代码:
import json
from urllib import request
OD=open('od_walking.txt').read().splitlines()
url_base='https://restapi.amap.com/v5/direction/bicycling?parameters&key=47e4ca6d9cd2c2e62b9e300dcd1a8370&origin={0},{1}&destination={2},{3}'
output=open('one_wsy.txt','wb')
for i in OD:
x1,y1,x2,y2=i.split('\t')
url=url_base.format(x1,y1,x2,y2)
try:
html=request.urlopen(url,timeout=15).read()
js=json.loads(html)
route = js.get('route')
if route is not None:
paths = route.get('paths')
if paths is not None:
path = paths[0]
d = path.get('distance')
if d is not None:
c = path.get('cost', {}).get('duration')
out='{0}\t{1}\n'.format(d,c)
output.write(out.encode('utf8'))
else:
print("No 'paths' in 'route'")
else:
print("No 'route' in JSON")
except Exception as e:
print(repr(e))
output.write(url.encode('utf8'))
output.close()
这样,当'route'
、'paths'
、'distance'
或者'cost'
键不存在时,你的代码不会抛出KeyError,而是会默认为None或者执行相应的错误处理
【以下回答由 GPT 生成】
这个KeyError错误是由于在解析返回的JSON数据时,找不到指定的键造成的。具体来说,当使用js['route']['paths'][0]['distance']
和js['route']['paths'][0]['cost']['duration']
时,如果在JSON中没有找到对应的键,就会出现KeyError。
解决该问题的方法是在访问JSON数据之前,先进行检查以确保所需的键存在。
以下是修改后的代码片段:
import json
from urllib import request
OD=open('od_walking.txt').read().splitlines()
url_base='https://restapi.amap.com/v5/direction/bicycling?parameters&key=47e4ca6d9cd2c2e62b9e300dcd1a8370&origin={0},{1}&destination={2},{3}'
output=open('one_wsy.txt','wb')
for i in OD:
x1,y1,x2,y2=i.split('\t')
url=url_base.format(x1,y1,x2,y2)
try:
html=request.urlopen(url, timeout=15).read()
js=json.loads(html)
if 'route' in js and 'paths' in js['route'] and len(js['route']['paths']) > 0:
d=js['route']['paths'][0].get('distance', '')
c=js['route']['paths'][0]['cost'].get('duration', '')
out='{0}\t{1}\n'.format(d,c)
output.write(out.encode('utf8'))
else:
output.write(url.encode('utf8'))
except Exception as e:
print(repr(e))
output.write(url.encode('utf8'))
output.close()
这里使用了if
语句来检查JSON中是否存在'route'
、'paths'
和存在至少一个路径的判断。然后使用.get()
方法来获取距离和持续时间,如果键不存在则返回一个空字符串。这样就可以避免出现KeyError异常。