简体   繁体   English

Python包:根据地址获取国家/地区(非IP)

[英]Python Package: Get the country based on adress(non-ip)

I'm searching for python package that can help me get the country from the address. 我正在寻找可以帮助我从地址获取国家的python包。

I use pycountry but I could used only if I have the country in the address, but I don't know what to do if I have, for ex: 我使用pycountry但我只能在地址中有国家的情况下使用,但如果有的话,我不知道该怎么办,例如:

"Georgetown, TX" , "Santa Fe, New Mexico", "Nuremberg", "Haarbergstr. 67 D-99097 Erfurt". “Georgetown,TX”,“Santa Fe,New Mexico”,“Nuremberg”,“Haarbergstr.67 D-99097 Erfurt”。

I don't know what to do when I have no country in address, and no clear pattern. 当我没有国家的地址,没有明确的模式时,我不知道该怎么办。

Seems geopy can do it relatively easily. 看似geopy可以相对容易地做到这一点。 An example adopted from the 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'

We got it! 我们得到了它! Now, test it on other locations 现在,在其他位置进行测试

>>> 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'

So you could automate the list in a script: 所以你可以在脚本中自动化列表:

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)

Output: 输出:

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

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM