列出迭代异常以便循环继续进行,地理编码
list iterating exception so the loop keeps going, geocode
我有一个地名列表,我想遍历它以获取坐标:
import time
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="xxx")
for a in pl:
location = geolocator.geocode(a)
print(location.latitude)
time.sleep(2)
现在它适用于前几个条目,然后出现以下错误:
AttributeError: 'NoneType' object has no attribute 'latitude'
我假设该特定条目的格式无法解释。在这些情况下,我怎样才能让我的循环继续下去,只是将这些条目保留为黑色,或者直接删除条目。
将对 location.latitude
的访问包装在 try/except 块中:
for a in pl:
location = geolocator.geocode(a)
try:
print(location.latitude)
except AttributeError:
print('Skipping bad location...')
time.sleep(2)
你可以检查位置是否不是None,然后只从中获取纬度属性
import time
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="xxx")
for a in pl:
location = geolocator.geocode(a)
#If location is not None, print latitude
if location:
print(location.latitude)
time.sleep(2)
我有一个地名列表,我想遍历它以获取坐标:
import time
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="xxx")
for a in pl:
location = geolocator.geocode(a)
print(location.latitude)
time.sleep(2)
现在它适用于前几个条目,然后出现以下错误:
AttributeError: 'NoneType' object has no attribute 'latitude'
我假设该特定条目的格式无法解释。在这些情况下,我怎样才能让我的循环继续下去,只是将这些条目保留为黑色,或者直接删除条目。
将对 location.latitude
的访问包装在 try/except 块中:
for a in pl:
location = geolocator.geocode(a)
try:
print(location.latitude)
except AttributeError:
print('Skipping bad location...')
time.sleep(2)
你可以检查位置是否不是None,然后只从中获取纬度属性
import time
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="xxx")
for a in pl:
location = geolocator.geocode(a)
#If location is not None, print latitude
if location:
print(location.latitude)
time.sleep(2)