gpt4 book ai didi

python - 返回使用geopy和try/except时引发AttributeError的项目列表?

转载 作者:行者123 更新时间:2023-12-03 08:50:07 26 4
gpt4 key购买 nike

我正在尝试使用geopy获取约400个位置的纬度和经度。但是,许多地址返回的是“None”,因为它们不够具体或者是街道的交叉点,这导致了“AttributeError:'None'类型没有属性'latitude'”和for循环的退出。

我想做的是运行for循环而不会由于错误而退出,并返回所有提示错误的位置的列表,以便我可以为它们硬编码一个正确的地址。

我当前的代码如下:

from geopy.geocoders import Nominatim
geolocator = Nominatim()
coordinates = []

def station_errors(list_of_stations):
for station in list_of_stations:
try:
location = geolocator.geocode(str(i)) #line with error, used 'i' instead of 'station'
lat_long = (location.latitude, location.longitude)
coordinates.append(list(lat_long))
except Exception:
print("Error: %s"%(station))
continue

但是,这似乎正在打印出每个站,而不管geopy是否能够为其指定纬度和经度,因为我已经手动尝试了许多。我只希望出现错误的站/无法接收经纬度坐标。

我对“尝试,但继续”错误测试还很陌生,因此非常感谢您提供任何建议。

编辑:

我最初的错误是使用“i”而不是“station”,这是我在原始问题中留下的错误。我需要工作并为我提供所需结果的代码如下:
def station_errors(list_of_stations):
list_of_error_stations = []
for station in list_of_stations:
try:
location = geolocator.geocode(str(station + " DC"))
lat_long = (location.latitude, location.longitude)
coordinates.append(list(lat_long))
except Exception:
list_of_error_stations.append(station)
continue
return(list_of_error_stations)

最佳答案

我希望在该行中给出“AttributeError:'None'类型没有属性'latitude'”:

lat_long = (location.latitude, location.longitude)

我会用以下方式转换代码:
def station_errors(list_of_stations):
for station in list_of_stations:
location = geolocator.geocode(str(i))
coordinates.append([location.latitude, location.longitude] if location is not None else None)
# or coordinates.append(list(lat_long) if location is not None else [None, None])
# which ever comes more in handy
return coordinates

coords = station_errors(los)
# and then deal with the Nones (or [None, None] s ) to "hard code a proper address for them"

关于python - 返回使用geopy和try/except时引发AttributeError的项目列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43380568/

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