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")))
执行程序,可以看到
这条信息
这条信息, 哈哈