2017-08-17 66 views
1

我從一個文件中讀取了更多的千位座標,爲此我想獲取相關國家。我試圖殺死時間限制,但它不起作用,它在150-160座標後停止。我可以處理這個嗎?Python,geopy kill time limit

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
import os, sys 


with open('alagridsor.txt') as f: 
    lines = f.read().splitlines()  


for sor in range(1, 9271): 
    print(sor) 

    koor = lines[sor] 

    from geopy.geocoders import Nominatim 
    from geopy.exc import GeocoderTimedOut 

    geolocator = Nominatim() 
    location = geolocator.reverse(koor, timeout=None) 
    cim = location.raw['address']['country'] 

    print(cim) 

    f = open('out.txt', 'a') 
    f.write(cim.encode('utf8')) 
    f.write("\n") 

回答

2

問題

  1. 使用f.read()和忽略的大小將導致文件的全部內容被讀取並返回。如果文件是機器內存的兩倍,則會遇到問題。
  2. 在for循環中始終打開輸出文件非常昂貴。

可能的解決方案

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
import time 
from geopy.geocoders import Nominatim 

geolocator = Nominatim(timeout=None) 
fobj_out = open('out.txt', 'a') 
with open('alagridsor.txt') as fobj_in: 
    for koor in fobj_in: 
     location = geolocator.reverse(koor.rstrip()) 
     cim = location.raw['address']['country'] 
     fobj_out.write(cim.encode('utf8')) 
     fobj_out.write("\n") 
     time.sleep(0.5)  # delay 5 milli-seconds between each request 
fobj_out.close() 
+0

非常感謝您!我會盡快嘗試... –

+0

它寫道:「預計一個縮進塊」爲koor.rstrip()行 –

+0

沒有,我工作了...... :) –