赞
踩
gettext是兼容GNU gettext的国际化模块,使用纯Pyhton实现。
first_gettext.py:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import gettext
# 一些设置
t = gettext.translation(
'first', 'locale',
fallback=True,
)
_ = t.gettext # 一般使用_,简单方便
print(_('This message is we want to translate.'))
运行:
deepin@deepin-PC:~/source/demo/python$ python3 first_gettext.py
This message is we want to translate.
我们还没有添加其他的语言支持,在这种情况下如果fallback为True,那么直接使用内置_中的字符串,如果fallback为False,返回“找不到翻译文件”异常:
deepin@deepin-PC:~/source/demo/python$ python3 first_gettext.py
Traceback (most recent call last):
File "first_gettext.py", line 9, in <module>
fallback=False,
File "/usr/lib/python3.5/gettext.py", line 529, in translation
raise OSError(ENOENT, 'No translation file found for domain', domain)
FileNotFoundError: [Errno 2] No translation file found for domain: 'first'
提取源文件中使用的字符串(使用pygettext.py,或使用GUN gettext中的工具):
xgettext -o first.po first_gettext.py --from-code utf-8
生成的first.po,文件名和代码中translation第一个参数对应:
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2017-11-30 14:51+0800\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"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"
#: first_gettext.py:13
msgid "This message is we want to translate."
msgstr ""
修改文件中信息,姓名、邮件、版本等等;charset改为UTF-8;然后翻译:
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2017-11-30 14:19+0800\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"
"Language: zh_CN\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: first_gettext.py:13
msgid "This message is we want to translate."
msgstr "这是我们要翻译的消息"
源码中translation第二个参数代表翻译文件保存路径,创建目录结构:
mkdir -p locale/zh_CN/LC_MESSAGES
mv first.po locale/zh_CN/LC_MESSAGES
cd locale/zh_CN/LC_MESSAGES
创建mo文件:
msgfmt -o first.mo first.po
在中文环境运行我们程序进行测试:
deepin@deepin-PC:~/source/demo/python$ python3 first_gettext.py
这是我们要翻译的消息
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。