我正在搜索可以帮助我从该地址获取国家的python包。
我使用pycountry但我只能在地址中有国家的情况下使用,但如果有的话,我不知道该怎么办,例如:
" Georgetown,TX" ," Santa Fe,New Mexico"," Nuremberg"," Haarbergstr。 67 D-99097 Erfurt"。
当我没有国家的地址,没有明确的模式时,我不知道该怎么做。
答案 0 :(得分: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
希望这有帮助。