0

我想从 python 中的变量翻译文本。

country = input(" Please choose a contry tagg (like fr, us...) :")

我想翻译文本用户输入,例如:

fr = France
us = USA

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

我想把它翻译成有效的国家,比如:法国、美国等。

我怎样才能做到这一点 ?

4

3 回答 3

1

您可以尝试pycountry在命令行中运行模块,pip install 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

有关更多信息,请参阅

于 2021-03-24T20:34:26.283 回答
0

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

为了为 I18N 准备代码,您需要查看文件中的所有字符串。任何需要翻译的字符串都应该通过将其包装在 _('...') 中来标记——即调用函数 _()。例如:

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

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

于 2021-03-24T20:21:57.217 回答
0

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

转换很容易,例如:

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"]

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

于 2021-10-15T15:04:29.260 回答