python gettext使用

发布时间:2019-09-26 12:30:18编辑:auto阅读(4199)


    python中使用gettext进行语言国际化的方法

    1.编辑源代码, 保存为gettextdemo.py

    import gettext
    catalogs = gettext.find("example", localedir="locale", all=True)
    print 'catalogs:',catalogs
    t = gettext.translation('example', "locale", fallback=True)
    _=t.ugettext
    print(_("this message"))
    

    2.从源代码中抽取需要国际化的文本消息,并转换创建.pot文件, 可以使用的工具为pygettext.py 或者GNU工具 xgettext

    里我使用xgettext,  MAC上使用homebrew 安装, 输入命令:

    >brew install xgettext

    即可自动完成安装, 安装后的默认目录:/usr/local/Cellar/gettext/0.19.2/, 

    进入/usr/local/Cellar/gettext/0.19.2/bin 可以看到有很多可执行文件 , 我们这里需要用到xgettext 和 msgfmt

    回到正题, 输入以下命令生成example.pot文件

    xgettext -o example.pot gettextdemo.py

    3.将example.pot复制到./local/en_US/LC_MESSAGES/example.po, 修改这个文件,替换要国际化的消息内容

    如把

    msgid "this message"
    msgstr "translated message"

    修改为:

    <pre name="code" class="html">msgid "this message"
    msgstr "translated message"

    4.将po文件转换成.mo 二进制文件, 
    

    cd locale/en_US/LC_MESSAGES/
    msgfmt -o example.mo example.po
    可以看到转换后生成的mo是二进制文件,而po,pot都是文本文件

    这一步很关键,我在弄的时候没注意到这一步, 直接把.po文件复制成.mo文件, 导致出现以下类似的情况, 掉到坑里,半天爬不出来,汗~

    File "C:\env\lib\gettext.py", line 281, in _parse
        raise IOError(0, 'Bad magic number', filename)
    IOError: [Errno 0] Bad magic number: 'advbus/locale\\ja\\LC_MESSAGES\\noname.mo'










    参考资料:

    1.<python标准库> 15.1.3

关键字