2015-07-19 48 views
0

我正在使用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拋出超時。呼叫。城市有「曼徹斯特」,「紐約,紐約」或類似的東西 。 我已經試過了 - 除了所有東西外都有塊,但是這並沒有改變任何關於這個問題的東西,所以我現在就把它們刪除了......任何想法都會很棒!

+1

無關但是'如果位置不是無:'會更可讀 –

+0

你試圖增加超時嗎? geolocator.geocode(city,timeout = 10); – nxpnsv

+0

即使超時時間= 10,我仍然收到錯誤。 如果我運行代碼5次,我通常會得到3-4次的錯誤,另外1-2次它工作得很好,儘管它需要比它應該更長的時間。 –

回答

0

您將受到您所使用的任何geolocator服務的擺佈。 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) 

這將再次嘗試10次,1秒的延遲之後。根據自己的喜好調整這些數字。

如果您重複詢問同一個城市,則應考慮將其包裹在某種記憶中,例如, this decorator。 由於您尚未發佈可運行代碼,因此我無法對此進行測試。