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

标签 python python-2.7 country-codes

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

例如:

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 的正确方法

关于python - 从用户输入中使用 pycountry 获取国家代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40628490/

相关文章:

python-2.7 - 确定点是否在旋转矩形内(仅限标准 Python 2.7 库)

macos - Python 2.7 - 使用 Xvfb 进行 Selenium headless 测试不起作用

java - 获取给定电话号码的详细国家名称和国家代码

datetime - 如何从国家/地区获取时区

python - 如何避免按索引对数据透视表进行排序

python - 如何从 python 3 中的单个函数返回多个变量?

python - 如何从 Google 的自定义搜索 API 中提取搜索结果数量?

python - _mysql_exceptions.ProgrammingError 1064,“您的 SQL 语法有错误;请检查

python - 如何在 Python 中显示字符串的前几个字符?

c# - ISO和奥林匹克国家代码之间的映射?