如何在 Python 中将 gettext 用于多种语言?

How to use gettext in Python for multiple languages?

提问人:Оксана Третьякова 提问时间:11/3/2023 最后编辑:Danila GancharОксана Третьякова 更新时间:11/3/2023 访问量:38

问:

我的任务是使用 Python 中的库来支持我的项目中的多种语言。我已经为每种支持的语言创建了文件,它们位于“translations”目录中。gettext.po.mo

我的目标是根据用户的选择在语言之间切换,并在我的应用程序中显示相应的文本。

这是我尝试过的一段代码:

import gettext

# Make sure you have all the .po and .mo files
# Make sure all .po and .mo files are in the correct directory.

# Create a list of supported languages
supported_languages = ['ar', 'ru']

for lang in supported_languages:
    translation = gettext.translation('messages', localedir='translations', languages=[lang])
    _ = translation.gettext
    translation.install()

# Example of a shortened text for the prompt (Hello World)
SYSTEM_PROMPT_MESSAGE = _("Hello World")
print(SYSTEM_PROMPT_MESSAGE)

但是,我遇到了困难,无论选择哪种语言,应用程序始终以英语显示文本。我做错了什么?如何在 Python 中正确使用多种语言?gettext

python gettext

评论

1赞 tripleee 11/3/2023
你试过文档吗?

答: 暂无答案