Python包:基于地址获取国家(非ip)

2024-05-29 03:58:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在搜索python包,它可以帮助我从地址中获取国家信息

我使用pycountry,但我只能在地址中有国家时使用,但如果有,我不知道该怎么办,例如:

“乔治敦,德克萨斯州”,“圣达菲,新墨西哥州”,“纽伦堡”,“哈尔贝格斯特尔。67 D-99097“爱尔福特”

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


Tags: 信息地址模式国家pycountry
1条回答
网友
1楼 · 发布于 2024-05-29 03:58:49

似乎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

希望这有帮助

相关问题 更多 >

    热门问题