从用户输入中使用 pycountry 获取国家代码

Get country code using pycountry from a user input

我正在尝试将国家名称转换为所需的国家代码。

例如:

United Kingdom : UK

我尝试了以下操作:

import pycountry
user_input = raw_input(': ')
mapping = {country.name: country.alpha2 for country in pycountry.countries}
print mapping.get(user_input)

我认为我可能误解了文档,因为我收到以下错误:

    mapping = {country.name: country.alpha2 for country in pycountry.countries}
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pycountry/db.py", line 22, in __getattr__
    raise AttributeError
AttributeError
import pycountry
user_input = raw_input(': ')
mapping = {country.name: country.alpha_2 for country in pycountry.countries}
print mapping.get(user_input)

是您使用 'alpha2' 而不是 alpha_2

的正确方法

对于Python3,相信使用Pytz内置模块会更简单

>> import pytz
>> print(pytz.country_names['tn'])
Tunisia