2013-11-22 41 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和更早的版本仍然有這個

問題