Geopy太慢超时所有时间

2024-10-01 15:45:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用geopy来获取城市名称的经纬度对。 对于单个查询,这很好。我现在要做的是迭代 一个大名单的城市名称(46.000)和每个城市的地理代码。然后,我通过一个check循环运行它们,该循环将城市(如果它在美国)排序为正确的状态。我的问题是,我得到“GeocoderTimedOut('Service timed out')” 一直以来,一切都很缓慢,我不确定这是我的错还是地质的自然。 下面是负责任的代码片段:

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就抛出超时。打电话。城市有形式 “曼彻斯特”,“纽约,纽约”之类的。 我已经试过了-除了所有的障碍物,但这并不能真正改变问题的任何方面,所以我暂时把它们移除了。。。任何想法都太好了!在


Tags: the代码in名称cityfordatalen
2条回答

你将任凭你所使用的地理定位服务。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。 因为你还没有发布一个可运行的代码,我无法测试这个。在

你应该改变你的路线:

location = geolocator.geocode(city);

^{2}$

相关问题 更多 >

    热门问题