美文网首页
python中国际化的简单使用

python中国际化的简单使用

作者: 氕氘氚0921 | 来源:发表于2019-12-20 16:23 被阅读0次

python中国际化首先需要翻译文件

msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-12-12 11:45+0800\n"
"PO-Revision-Date: 2019-12-12 17:33+0800\n"
"Language: zh_CN\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Last-Translator: \n"
"Language-Team: \n"
"X-Generator: Poedit 2.0.6\n"

msgid "this message"
msgstr "这条信息"

msgid "this message, hehe"
msgstr "这条信息, 哈哈"

将它命名为test.po。po文件是无法直接被程序所使用的,因此需要使用msgfmt工具,对po文件进行处理。

msgfmt -o test.mo test.po

通过改工具,我们将test.po处理为test.mo文件。将这一文件放在对应的语言翻译目录下,如

{project}/locale/zh_CN/LC_MESSAGES

python代码如下

import os
import gettext
import locale

root_path = os.path.dirname(os.path.dirname(__file__))
tools_locale_path = os.path.join(root_path, "locale")

languages = os.getenv("LANG", locale.getlocale()[0])

es = gettext.translation('tools',     localedir=tools_locale_path, languages=[languages])
es.install()

print(_("this message"))
print(_("this message, %s" % ("hehe")))

执行程序,可以看到

这条信息
这条信息, 哈哈

相关文章

网友评论

      本文标题:python中国际化的简单使用

      本文链接:https://www.haomeiwen.com/subject/vodinctx.html