2017-03-06 83 views
1

我正在寻找可以帮助我从地址获取国家的python包。Python包:获取基于地址的国家(非ip)

我用pycountry,但如果我在地址的国家,我只能用,但我不知道,做什么,如果我有恩:

“乔治城,TX”,“圣达菲,新墨西哥州“,”纽伦堡“,”Haarbergstr。67 D-99097爱尔福特“。

我不知道该怎么办,当我没有国家的地址,并没有明确的模式。

回答

3

似乎geopy可以做到这一点比较容易。从documentation采用的示例:

>>> import geopy 
>>> from geopy.geocoders import Nominatim 
>>> gl = Nominatim() 
>>> l = gl.geocode("Georgetown, TX") 
    # now we have l = Location((30.671598, -97.6550065012, 0.0)) 
>>> l.address 
[u'Georgetown', u' Williamson County', u' Texas', u' United States of America'] 
# split that address on commas into a list, and get the last item (i.e. the country) 
>>> l.address.split(',')[-1] 
u' United States of America' 

我们知道了!现在,测试它的其它位置

>>> l = gl.geocode("Santa Fe, New Mexico") 
l.address.split(',')[-1] 
u' United States of America' 
>>> l = gl.geocode("Nuremberg") 
>>> l.address.split(',')[-1] 
u' Deutschland' 
>>> l = gl.geocode("Haarbergstr. 67 D-99097 Erfurt") 
>>> l.address.split(',')[-1] 
u' Europe' 

所以,你可以在脚本中自动列表:

import geopy 
from geopy.geocoders import Nominatim 

geolocator = Nominatim() 

list_of_locations = "Georgetown, TX" , "Santa Fe, New Mexico", "Nuremberg", "Haarbergstr. 67 D-99097 Erfurt" 

for loc in list_of_locations: 
    location = geolocator.geocode(loc) 
    fulladdress = location.address 
    country = fulladdress.split(',')[-1] 
    print '{loc}: {country}'.format(loc=loc, country=country) 

输出:

Georgetown, TX: United States of America 
Santa Fe, New Mexico: United States of America 
Nuremberg: Deutschland 
Haarbergstr. 67 D-99097 Erfurt: Europe 

希望这有助于。

+0

geopy在大多数情况下不起作用,例如宽度:“A.J. Tuck Co. Brookfield,Ct United States 06804-1814”。肯定是和美国的地址,但结果是没有;这是工作,如果我删除公司名称和编号,但它并没有帮助我,因为我没有一个清晰的模式,如公司名称从地址 – user3541631

+0

删除字符串例如,已经在国家的字符串,可以你只是从字符串中提取国家?使用字符串分析,或正则表达式? – davedwards

+0

1)是的,但这意味着我必须建立自己的国家名单及其名称变体; - 我可以使用pycountry,但是 - > 2)如果我删除国家形式的字符串,我也会收到没有,所以1)不是主要问题,仅仅是一个例子; 3)与包装本身无关,而是与服务有关的问题 - 我尝试了更多的包装,每个包装都有不同的问题,并针对国家使用不同的名称,所以回收更难; 4)Nominatim作为响应时间最好,GoogleV3和雅虎收到了很多超时时间。 – user3541631