我是一个相对新的Python用户,正在尝试使用“geopy”模块的函数返回城市和国家的纬度和经度。我因为城市名称拼写错误而遇到了错误,但现在遇到了超时错误。我阅读了这个问题Geopy: catch timeout error并相应地调整了超时参数。然而,它现在会在不同的时间长度内运行,然后我会得到一个超时错误。我尝试在更快的网络上运行它,并且它在一定程度上起作用。问题是我需要对10万行数据做这个操作,而最大迭代行数为2万,导致程序超时。非常感谢任何帮助和建议来解决这个问题。
import os
from geopy.geocoders import Nominatim
os.getcwd() #check current working directory
os.chdir("C:\Users\Philip\Documents\HDSDA1\Project\Global Terrorism Database")
#import file as a csv
import csv
gtd=open("gtd_original.csv","r")
csv_f=csv.reader(gtd)
outf=open("r_ready.csv","wb")
writer=csv.writer(outf,dialect='excel')
for row in csv_f:
if row[13] in ("","NA") or row[14] in ("","NA"):
lookup = row[12] + "," + row[8] # creates a city,country
geolocator = Nominatim()
location = geolocator.geocode(lookup, timeout = None) #looks up the city/country on maps
try:
location.latitude
except:
lookup = row[8]
location = geolocator.geocode(lookup)
row[13] = location.latitude
row[14] = location.longitude
writer.writerow(row)
gtd.close()
outf.close()