我正在寻找可以帮助我从地址获取国家/地区的 python 包。
我使用 pycountry,但只有在地址中有国家/地区时我才能使用,但如果有,我不知道该怎么办,例如:
“德克萨斯州乔治敦”、“新墨西哥州圣达菲”、“纽伦堡”、“Haarbergstr. 67 D-99097 埃尔福特”。
当我的地址中没有国家/地区且没有明确的模式时,我不知道该怎么办。
最佳答案
似乎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
希望这有帮助。
关于Python包: Get the country based on adress(non-ip),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42631994/