Python本地化例子 - gettext 模块
关键字:Python 3.4,gettext,本地化,Localization
OS:Windows 7,Mac
1. 创建一个locsample.py文件,文件内容如下,把所有需要本地化的字符串放到_()里面。
# Python Localization Sample import os, gettext # Support localization _ = None def getUserLanguage(): return "zh-CN" # Get loc string by language def getLocStrings(): currentDir = os.path.dirname(os.path.realpath(__file__)) return gettext.translation('resource', currentDir, [getUserLanguage(), "en-US"]).gettext _ = getLocStrings() print(_("Hello"))
注意: 注意‘resource’是资源文件的名字,例如:'resource.mo'。getUserLanguage() 返回需要显示的语言,"en-US"作为备份,如果找不到对应语言的资源文件,就使用"en-US"。
2.pygettext.py在python安装目录下 \Tools\i18n 文件夹里面。 使用pygettext.py从py文件中提取所有被标记成需要本地化的字符串,也就是在_()里面的字符串。 例如:
运行“python pygettext.py -o resource.pot locsample.py”生成resource.pot。
运行“python pygettext.py -o resource.pot locsample.py”生成resource.pot。
3. 把resource.pot改名为resource.po,为每种语言拷贝一份resource.po,zh-CN的resource.mo内容修改如下:
# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR ORGANIZATION # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "POT-Creation-Date: 2015-08-04 12:47+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: 8bit\n" "Generated-By: pygettext.py 1.5\n" #: msgid "Hello" msgstr "你好"
en-US的resource.mo内容如下:
# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR ORGANIZATION # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "POT-Creation-Date: 2015-08-04 12:47+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: 8bit\n" "Generated-By: pygettext.py 1.5\n" #: msgid "Hello" msgstr "Hello"
4. 为各种语言创建gettext可读的.mo文件,使用msgfmt.py, 例如:
运行"python msgfmt.py -o resource.mo resource.po"生成resource.mo。mo文件是一个二进制文件。
5.把所有文件按照以下文件夹结构放置。
6. 运行locsample.py,输出:
你好
代码:
/************************************
ldlchina
QQ:3110615
************************************/