在gtk窗口中的matplotlib支持i18n(gettext)

时间:2013-11-22 20:19:23

标签: matplotlib internationalization pygtk gettext

我正在尝试使用gettext的_(“label”)构造来显示带有轴标记的matplotlib图。试图创建一个最小的例子,我想出了以下python代码。它通过NULLTranslations()运行良好,如下所示:

python mpl_i18n_test.py

但是当我切换到日语时,我只得到了剧情中的小方块 - 虽然在命令行上,翻译看起来很好:

LANG = ja_JP.utf8 python mpl_i18n_test.py

这是文件mpl_i18n_test.py 请注意,这需要安装mona-sazanami字体,以及各种python模块:pygtk,numpy,matplotlib,gettext和polib

所以我的问题:是否有一些技巧让matplotlib与gettext很好地配合?我错过了一些明显的东西吗?谢谢。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import unicode_literals

import gtk

import numpy as np
import matplotlib as mpl

from matplotlib.figure import Figure
from matplotlib.backends.backend_gtkagg import \
    FigureCanvasGTKAgg as FigureCanvas
from matplotlib.backends.backend_gtkagg import \
    NavigationToolbar2GTKAgg as NavigationToolbar

import locale
import gettext
import polib

mpl.rcParams['font.family'] = 'mona-sazanami'

def append(po, msg):
    occurances = []
    for i,l in enumerate(open(__file__,'r')):
        if "_('"+msg[0]+"')" in l:
            occurances += [(__file__,str(i+1))]
    entry = polib.POEntry(msgid=msg[0],
                          msgstr=msg[1],
                          occurrences=occurances)
    print msg
    print occurances
    po.append(entry)

def generate_ja_mo_file():
    po = polib.POFile()
    msgs = [
        (u'hello', u'こんにちは'),
        (u'good-bye', u'さようなら'),
        ]
    for msg in msgs:
        append(po, msg)

    po.save('mpl_i18n_test.po')
    po.save_as_mofile('mpl_i18n_test.mo')
    return 'mpl_i18n_test.mo'

def initialize():
    '''prepare i18n/l10n'''
    locale.setlocale(locale.LC_ALL, '')
    loc,enc = locale.getlocale()
    lang,country = loc.split('_')

    l = lang.lower()
    if l == 'ja':
        filename = generate_ja_mo_file()
        trans = gettext.GNUTranslations(open(filename, 'rb'))
    else:
        trans = gettext.NullTranslations()
    trans.install()

if __name__ == '__main__':
    initialize() # provides _() method for translations

    win = gtk.Window(gtk.WINDOW_TOPLEVEL)
    win.connect("destroy", lambda x: gtk.main_quit())
    win.connect("delete_event", lambda x,y: False)

    win.set_default_size(400,300)
    win.set_title("Test of unicode in plot")


    fig = Figure()
    fig.subplots_adjust(bottom=.14)
    ax = fig.add_subplot(1,1,1)
    xx = np.linspace(0,10,100)
    yy = xx*xx + np.random.normal(0,1,100)
    ax.plot(xx,yy)

    print 'hello --> ', _('hello')
    print 'good-bye --> ', _('good-bye')

    ax.set_title(u'こんにちは')
    ax.set_xlabel(_('hello'))
    ax.set_ylabel(_('good-bye'))

    can = FigureCanvas(fig)
    tbar = NavigationToolbar(can,None)

    vbox = gtk.VBox()
    vbox.pack_start(can, True, True, 0)
    vbox.pack_start(tbar, False, False, 0)

    win.add(vbox)


    win.show_all()
    gtk.main()

1 个答案:

答案 0 :(得分:0)

我发现解决方案只是在“安装”翻译时指定unicode。这是一个单行改变:

    trans.install(unicode=True)

我将补充一点,这只在python 2.7中需要,但在python 3中不需要。看起来像python 2.6及更早版本仍有问题