地理编码工具Geopy太慢,经常超时

3
我正在使用geopy获取城市名称的纬度-经度对。 对于单个查询,这很好用。现在我尝试遍历一个包含46,000个城市名称的大列表,并为每个城市获取地理编码。之后,我会将它们通过检查循环,将位于美国的城市(如果有的话)分类到正确的州。我的问题是,我一直收到“GeocoderTimedOut('服务超时')”的错误,所有东西都非常缓慢,我不确定是我的问题还是geopy的性质。以下是相关的代码片段:
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次调用时,这一行代码总是会超时。City的格式为"曼彻斯特"、"纽约,纽约"或类似形式。我已经在代码周围添加了try-except块,但这并没有真正解决问题,所以我现在已将其删除...希望有任何想法。


1
不相关的,但是如果位置不为None,代码会更易读。 - Padraic Cunningham
你尝试增加超时时间了吗?geolocator.geocode(city, timeout=10); - nxpnsv
即使设置了超时时间为10,我仍然会收到错误信息。 如果我运行代码5次,通常会出现3-4次错误,另外1-2次可以正常工作,尽管需要比应该的时间更长一些。 - Tobias Petri
2个回答

3

您将取决于您使用的地理定位服务。 geopy 只是不同网络服务的封装器,因此如果服务器繁忙,可能会失败。 我会创建一个 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)

这将尝试10次,每次间隔1秒。根据您的喜好调整这些数字。

如果您重复请求相同的城市,应考虑将其包装在某种记忆化中,例如此装饰器。 由于您没有发布可运行的代码,我无法测试此功能。


1
你应该改变你的代码行:
location = geolocator.geocode(city);

to

location = geolocator.geocode(city,timeout=None);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接