简介
Python通过gettext模块支持国际化(i18n),可以实现程序的多语言界面的支持。
详解
Linux下Python的国际化编程
在Linux的操作和C语言的国际化过程是一样的,在需要国际化的字符串前面添加_()即可。
(1)代码:internation.py
# -*- coding: utf-8 -*- #!/usr/bin/env python import gettext locale_path = './locale/' #gettext.install('internation', locale_path) # 这条语句会将_()函数自动放到python的内置命名空间中 zh_trans = gettext.translation('internation', locale_path, languages=['zh_CN']) en_trans = gettext.translation('internation', locale_path, languages=['en_US']) print "----中文版本----" zh_trans.install() print _("Hello world!") print _("Python is a good Language.") print "----英文版本----" en_trans.install() print _("Hello world!") print _("Python is a good Language.")
(2)生成po文件
1 方法1: 2 xgettext -k_ -o internation.po_en internation.py 3 xgettext -k_ -o internation.po_zh internation.py 4 5 6 方法2: 7 find . -type f \( -name '*.py' \) -print > list 8 xgettext --files-from=list -d internation -o internation.po --from-code=UTF-8
(3)翻译(charset设定为utf-8)
英文:
1 # SOME DESCRIPTIVE TITLE. 2 # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER 3 # This file is distributed under the same license as the PACKAGE package. 4 # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. 5 # 6 #, fuzzy 7 msgid "" 8 msgstr "" 9 "Project-Id-Version: PACKAGE VERSION\n" 10 "Report-Msgid-Bugs-To: \n" 11 "POT-Creation-Date: 2015-10-08 22:06+0800\n" 12 "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" 13 "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" 14 "Language-Team: LANGUAGE <LL@li.org>\n" 15 "MIME-Version: 1.0\n" 16 "Content-Type: text/plain; charset=UTF-8\n" 17 "Content-Transfer-Encoding: 8bit\n" 18 19 #: internation.py:11 internation.py:16 20 msgid "Hello world!" 21 msgstr "translate:Hello world" 22 23 #: internation.py:12 internation.py:17 24 msgid "Python is a good Language." 25 msgstr "translate:python is a good Language."
中文:
1 # SOME DESCRIPTIVE TITLE. 2 # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER 3 # This file is distributed under the same license as the PACKAGE package. 4 # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. 5 # 6 #, fuzzy 7 msgid "" 8 msgstr "" 9 "Project-Id-Version: PACKAGE VERSION\n" 10 "Report-Msgid-Bugs-To: \n" 11 "POT-Creation-Date: 2015-10-08 22:06+0800\n" 12 "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" 13 "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" 14 "Language-Team: LANGUAGE <LL@li.org>\n" 15 "MIME-Version: 1.0\n" 16 "Content-Type: text/plain; charset=utf-8\n" 17 "Content-Transfer-Encoding: 8bit\n" 18 19 #: internation.py:11 internation.py:16 20 msgid "Hello world!" 21 msgstr "您好!" 22 23 #: internation.py:12 internation.py:17 24 msgid "Python is a good Language." 25 msgstr "Python是一种好语言。"
(4)建立翻译文件路径
在主文件目录下建立英文翻译路径./locale/en_US/LC_MESSAGES/和中文翻译路径./locale/zh_CN/LC_MESSAGES/ (对文件层次比较严格)。
(5)生成mo最终文件
msgfmt -o ./locale/en_US/LC_MESSAGES/internation.mo internation.po_en
msgfmt -o ./locale/zh_CN/LC_MESSAGES/internation.mo internation.po_zh
(6)运行
。。。
Locale directory 参考:
https://docs.openstack.org/oslo.i18n/latest/user/usage.html