2017-08-17 92 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

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