Python包: Get the country based on adress(non-ip)

标签 python python-3.x geolocation

我正在寻找可以帮助我从地址获取国家/地区的 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/

相关文章:

python - 如何在Python中覆盖列表中 float 的比较?

python - 如何在 Scikit 中计算多类分类的混淆矩阵?

python - 在 PIL 中更改图像的对比度

ruby-on-rails - Ruby On Rails - 地理编码器 - 接近条件

mongodb - Geonear 不工作 - mongodb?

python - Flask 不加载 CSS 文件..?

python - 如何用 pandas DataFrame 中的共享列值替换某些行?

python - 为什么我在 python 3.6 的 jupyter Notebook 中收到警告以及如何修复它们?

python - Python 中具有 2 个列表的 ListAccess(list) 类

ios - 为 phonegap iOS 创建地理定位插件以在后台运行