gettext
gettext 是一套 GNU下的国际化工具。主要有工具:
- xgettext: 从源码中抽取字符串,生成po文件(portable object)
- msgfmt: 将po文件编译成mo文件(machine object)
- gettext: 进行翻译
如果找不到gettext命令,或者找不到msgfmt命令。请重新安装一遍gettext套件。
ubuntu系统:
安装gettext
sudo apt-get install gettext
创建目录
mkdir -p locale/zh_CN/LC_MESSAGES
在刚才目录下创建 .po 文件
vim hello.po
hello.po 内容
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: 2007-01-18 09:55+China Standard Time\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: utf8\n"
"Generated-By: pygettext.py 1.5\n"
msgid "hello world"
msgstr "你好世界"
msgid "Good job, %s! Your math scores is %d !"
msgstr "干得漂亮 %s , 你的数学成绩是 %d !"
Po->mo(PO人能看懂的,MO机器能看懂的)
msgfmt locale/zh_CN/LC_MESSAGES/hello.po -o locale/zh_CN/LC_MESSAGES/hello.mo
Python中测试
# 只要有mo文件,就能翻译 # 路径如locale/zh_CN/LC_MESSAGES/hello.mo
# 在跟locale目录同一级别的地方运行ipython
>> import gettext
>> zh = gettext.translation("hello", "locale", languages=["zh_CN"])
>> zh.install()
>> _('hello world')
'你好世界'
*有参数的情况,保留参数占位符是比较明智的选择
test.py 文件
import gettext
myName = 'Kevin'
myscores = 111
zh = gettext.translation("hello", "locale", languages=["zh_CN"])
zh.install()
print(_('Good job, %s! Your math scores is %d !') % (myName, myscores))
#当你想用回原有英语的时候 使用lambda 处理"_"即可
_ = lambda s: s
print(_('Good job, %s! Your math scores is %d !') % (myName, myscores))
Output
python3.6 test.py
干得漂亮 Kevin , 你的数学成绩是 111 !
Good job, Kevin! Your math scores is 111 !
参考博文:https://blog.csdn.net/handsomekang/article/details/78747504