2017-04-12 27 views
0

我正在嘗試使用geopy獲取約400個位置的經度和緯度。但是,許多地址返回'None',因爲它們要麼不夠詳細,要麼是街道的交叉點,這會導致「AttributeError:'None'類型沒有屬性'latitude'」並退出for循環。返回使用geopy時引發AttributeError的項目列表並嘗試/除外?

我想要做的是運行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是否能夠爲它分配一個緯度和經度,打印出來,因爲我已經試過許多人手動。我只想要發生錯誤的站點/無法接收經緯度座標。

我對'嘗試,除了繼續'錯誤測試相當新,所以任何建議非常感謝。

編輯:

我最初的錯誤使用「我」而不是「站」,這是我一直留在原來的問題的錯誤。

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) 
+0

在該代碼,如果他們印製,你必須已經拋出異常。在您的手動測試中,您是否使用相同的代碼?我猜測geocode方法會導致一些連接錯誤 – Miquel

+0

地理編碼引發異常,但由於我的原因,我使用str(i)而不是str(station)。解決這個問題會打印出引發異常的每個工作站,可以將其重新格式化爲列表,因爲我將在編輯時演示我的原始問題。 – Martin

回答

0

我想到的是:我要工作,並給了我,我要的是如下的結果代碼「AttributeError的:‘無’類型沒有屬性‘緯度’」中給出行:

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" 
相關問題