2013-11-22 23 views
0

我试图用标签使用gettext的_(“标签”)构造来显示matplotlib图。试着创建一个最小的例子,我想出了下面的python代码。它贯穿于NULLTranslations()这样的罚款:matplotlib在gtk窗口中使用i18n(gettext)支持

蟒蛇mpl_i18n_test.py

但是当我切换到日本,我什么也没得到,但小方块中的情节 - 尽管在命令行中,译文看起来不错:

LANG = ja_JP.utf8蟒蛇mpl_i18n_test.py

这里是文件mpl_i18n_test.py 注意,这需要安装蒙娜丽莎-沦字体和各种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() 

回答

0

我找到的解决方案是只在翻译“安装”时指定unicode。这是一个单行的变化:

trans.install(unicode=True) 

我会补充说,这只是需要Python 2.7版,但是在Python 3不需要看起来像蟒蛇2.6和更早的版本仍然有这个

问题