如何从 Python 中给定的 ISO-3166-1 alpha-2 代码获取国家/地区名称?

How do I get the country name from a given ISO-3166-1 alpha-2 code in Python?

我希望用户输入 ISO-3166-1 alpha-2 代码。

country_code = input("Please enter a country's two-letter code (e.g. FR, US) :")

然后我想把代码翻译成国家的名字:

FR -> France
US -> United States of America

https://laendercode.net/en/2-letter-list.html

我该怎么做?

这称为“国际化”,执行此操作的 Python 模块是 gettext。例如:

In order to prepare your code for I18N, you need to look at all the strings in your files. Any string that needs to be translated should be marked by wrapping it in _('...') — that is, a call to the function _(). For example:

filename = 'mylog.txt'
message = _('writing a log message')
with open(filename, 'w') as fp:
    fp.write(message)

这是一个复杂的主题,该页面将为您提供大量信息作为开始。

您可以在命令行 运行 pip install pycountry 中尝试模块 pycountry,然后在您的代码中:

import pycountry
country_code = input(" Please choose a contry tagg (like fr, us...) :")
country = pycountry.countries.get(alpha_2=country_code)
country_name = country.name

有关详细信息,请参阅 this

您可以使用 country_converter,使用 pip install country_converter 安装。
pycountry 大约 10mb 相比,这大约是 50kb。

转换很容易,像这样:

import country_converter as coco
input_country = input(" Please choose a contry tagg (like fr, us...) :")
converted_country = coco.convert(names=input_country, to="name")
print(converted_country)
  • names可以是单数也可以是列表可以混合输入
    • names="fr"
    • names=["fr", "USA", "826", 276, "China"]

文档中列出了很多分类方案,可以作为输入或转换为.