我使用geopy来获取城市名称的经纬度对。对于单个查询,这可以很好地工作。我现在尝试做的是迭代通过一个大的城市名称列表(46.000),并获得每个城市的地理编码。然后,我通过一个检查循环运行它们,该循环将城市(如果它位于美国)排序为正确的州。我的问题是,我总是收到“GeocoderTimedOut(‘服务超时’)”,一切都很慢,我不确定这是我的错还是仅仅是地理位置的原因。以下是负责的代码片段:
for tweetcount in range(number_of_tweets):
#Get the city name from the tweet
city = data_dict[0]['tweetList'][tweetcount]['user']['location']
#Sort out useless tweets
if(len(city)>3 and not(city is None)):
# THE RESPONSIBLE LINE, here the error occurs
location = geolocator.geocode(city);
# Here the sorting into the state takes place
if location is not None:
for statecount in range(len(data)):
if point_in_poly(location.longitude, location.latitude, data[statecount]['geometry']):
state_tweets[statecount] += 1;
break;不知何故,这一行在每2./3次调用时抛出超时。城市有“曼彻斯特”,“纽约,纽约”或类似的形式。我已经尝试过了-除了所有东西周围的块,但这并没有真正改变问题的任何东西,所以我现在删除了它们……任何想法都会很棒!
发布于 2016-05-18 23:04:41
您将受到您正在使用的任何地理定位服务的摆布。geopy只是不同web服务的包装器,因此在服务器繁忙时可能会失败。我将在geolocator.geocode调用周围创建一个包装器,如下所示:
def geocode(city, recursion=0):
try:
return geolocator.geocode(city)
except GeocoderTimedOut as e:
if recursion > 10: # max recursions
raise e
time.sleep(1) # wait a bit
# try again
return geocode(city, recursion=recursion + 1)这将在延迟1秒后重试10次。根据您的喜好调整这些数字。
如果你反复要求相同的城市,你应该考虑用某种形式的记忆来包装它,例如this decorator。由于您还没有发布可运行的代码,因此我无法对此进行测试。
发布于 2019-02-14 19:25:25
您应该更改您的行:
location = geolocator.geocode(city);至
location = geolocator.geocode(city,timeout=None);https://stackoverflow.com/questions/31506272
复制相似问题