我一直在导入包含多个地址的csv数据集。我想得到这些地方的纬度和经度,并将它们与原始地址一起写入新的csv文件。我一直在尝试使用python中的Geopy来实现这一目标。以下是代码:
import csv
##from time import sleep
from geopy.geocoders import Nominatim
with open('D:/location_to_lat_lon/tolocate.csv', 'r') as fp:
with open('D:/location_to_lat_lon/places_located.csv', 'w',newline='') as op:
a = csv.writer(op)
a.writerow(["Town","District","State","Country","Address","Latitude","Longitude"])
for line in fp.readlines():
geolocator = Nominatim()
town_new = line.split(',')[0]
district_new = line.split(',')[1]
state_new = line.split(',')[2]
country_new = line.split(',')[3]
address_new = line.split(',')[4]
location = geolocator.geocode(address_new)
lat=location.latitude
lon=location.longitude
##time.sleep(3)
a.writerow([town_new,district_new,state_new,country_new,address_new,lat,lon])
但是,每次运行此代码时都会出现以下错误
回溯(最近一次呼叫最后一次):文件“”,第13行,中 lat = location.latitude AttributeError:'NoneType'对象没有属性'latitude
有谁可以帮我解决这个问题?
答案 0 :(得分:2)
由于各种原因,包括地理编码服务没有给定地址的地理空间数据,您忘记该位置有时可能为无。
simpley do
location = geolocator.geocode(address_new)
if location:
lat=location.latitude
lon=location.longitude
else :
lat = None
long = None
你也可以try, except
答案 1 :(得分:-2)
有时,实际位置,即纬度和经度不适用于特定地址。在这种情况下,你必须忽略这种地址。在你的代码中它应该是这样的 -
导入csv
从时间导入睡眠导入Nominatim
打开(' D:/location_to_lat_lon/tolocate.csv',' r')为fp:
with open('D:/location_to_lat_lon/places_located.csv', 'w',newline='') as op:
a = csv.writer(op)
a.writerow(["Town","District","State","Country","Address","Latitude","Longitude"])
for line in fp.readlines():
geolocator = Nominatim()
town_new = line.split(',')[0]
district_new = line.split(',')[1]
state_new = line.split(',')[2]
country_new = line.split(',')[3]
address_new = line.split(',')[4]
location = geolocator.geocode(address_new)
''' This will check if your given address has any latitude or longitude and if true then lat and lon will be assigned otherwise, both lat and lon will be 0. '''
if location:
lat=location.latitude
lon=location.longitude
##time.sleep(3)
else:
lat = 0
lon = 0
a.writerow([town_new,district_new,state_new,country_new,address_new,LAT,LON])`