我有一个函数,可以找到输入地址的纬度和经度。但由于有时一个地址什么也不返回(例如,在Google地图中找不到),我想从地址中一个接一个地删除单词,直到它最终可以返回一些东西。代码对所有地址都运行良好,但有几个地址除外,我在下面展示了其中一个地址:
place = '033 SEGOVIA ST ILAWOD 2 DARAGA ALBAY PHILIPPINES'
while True:
place = place.split(' ', 1)[1] # remove the first word from the address
try:
lat, lon, res = gmaps_geoencoder(place)
except:
place = place.split(' ', 1)[1]
lat, lon, res = gmaps_geoencoder(place)
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-174-5b96029e3dbf> in <module>()
5 try:
----> 6 lat, lon, res = gmaps_geoencoder(place)
7 except:
<ipython-input-1-3bfa8158ebff> in gmaps_geoencoder(address)
12 res = req.json()
---> 13 result = res['results'][0]
14 lat = result['geometry']['location']['lat']
IndexError: list index out of range
During handling of the above exception, another exception occurred:
IndexError Traceback (most recent call last)
<ipython-input-174-5b96029e3dbf> in <module>()
7 except:
8 place = place.split(' ', 1)[1]
----> 9 lat, lon, res = gmaps_geoencoder(place)
<ipython-input-1-3bfa8158ebff> in gmaps_geoencoder(address)
11 req = requests.get(GOOGLE_MAPS_API_URL+'?address='+address+'&key='+API_key)
12 res = req.json()
---> 13 result = res['results'][0]
14 lat = result['geometry']['location']['lat']
15 lon = result['geometry']['location']['lng']
IndexError: list index out of range
为什么它不能捕获这个地址的异常?为什么其他大多数的地址都是这样?你知道吗
当我手动尝试该功能时,它工作正常:
gmaps_geoencoder('033 SEGOVIA ST ILAWOD 2 DARAGA ALBAY PHILIPPINES')
产生错误
gmaps_geoencoder('SEGOVIA ST ILAWOD 2 DARAGA ALBAY PHILIPPINES')
产生错误
gmaps_geoencoder('ST ILAWOD 2 DARAGA ALBAY PHILIPPINES')
产生错误
但是gmaps_geoencoder('ILAWOD 2 DARAGA ALBAY PHILIPPINES')
正确返回位置坐标。你知道吗
p.S.:如果有关系,下面是我的函数定义:
def gmaps_geoencoder(address):
req = requests.get(GOOGLE_MAPS_API_URL+'?address='+address+'&key='+API_key)
res = req.json()
result = res['results'][0]
lat = result['geometry']['location']['lat']
lon = result['geometry']['location']['lng']
return lat, lon, str(res)
您的代码在except子代码中引发另一个
Exception
。你知道吗我同意这种方法
请注意,在某个时刻
try
成功了,您希望break
。另外,place
可以结束(可能是一个空列表),您可以在except
子代码下的break
处结束,或者将其作为while
中的停止项最后但并非最不重要的是,强烈建议不要在没有特定
except:
的情况下使用。我建议调查一下你想在那里抓住哪个Exceptions
。你知道吗下面是一个更经过处理的代码:
我故意不为您编写这段代码,因为我不知道您想用
lat, lon
做什么。你想得到第一个结果吗?或者结果列表?我留给您处理“未知”异常的基本结构。你知道吗相关问题 更多 >
编程相关推荐