列出迭代异常,以便循环继续进行,地址解析

时间:2019-06-23 19:48:17

标签: python loops exception 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'

我假设该特定条目的格式不能被解释。在这种情况下,如何使循环继续进行,只为这些输入保留黑色,或者直接删除该条目。

2 个答案:

答案 0 :(得分:1)

您可以检查location是否不是None,然后仅从中获取latitude属性

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)

答案 1 :(得分:0)

将对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)