问题描述
我想从 python 中的变量翻译文本。
country = input(" Please choose a contry tagg (like fr,us...) :")
我想翻译用户输入的文本,例如:
fr = France
us = USA
https://laendercode.net/fr/2-letter-list.html
我想将其翻译成有效的国家/地区,例如:法国、美国等
我该怎么做?
解决方法
您可以尝试模块 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
有关详细信息,请参阅 this
,这被称为“国际化”,执行此操作的 Python 模块是 gettext。例如:
为了为 I18N 准备代码,您需要查看文件中的所有字符串。任何需要翻译的字符串都应该通过将其包裹在 _('...') 中来标记——即调用函数 _()。例如:
filename = 'mylog.txt'
message = _('writing a log message')
with open(filename,'w') as fp:
fp.write(message)
这是一个复杂的主题,该页面将为您提供大量信息。