2012-03-22 57 views
4

我正在構建一個利用一堆翻譯後的字符串的Python應用程序。目錄結構住房表示字符串看起來是這樣的:由一個PHP應用程序生成Python和gettext

/locales 
    default.pot # reference English strings live here 
    /es_ES 
     /LC_MESSAGES 
      default.po #Spanish strings 
    /de_DE 
     /LC_MESSAGES 
      default.po #German strings 

這些default.po文件,但據我所知,它們符合與gettext實現工作所需的一般標準。

當我嘗試使用gettext的利用在Python這些字符串,下面的下降(本例中是從locales目錄中運行:

>>> import os; os.listdir('.') 
['.svn', 'de_DE', 'default.pot', 'eng', 'es_ES', 'fr_FR', 'ja_JP', 'ko_KR', 'pl_PL', 'pt_BR', 'ru_RU'] 
>>> import os.path 
>>> os.path.exists('./es_ES/LC_MESSAGES/default.po') 
True 
>>> import gettext 
>>> ldir = 'es_ES/LC_MESSAGES/' 
>>> t = gettext.translation('default',ldir) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/gettext.py", line 469, in translation 
IOError: [Errno 2] No translation file found for domain: 'default' 
>>> 

我不知道我在做什麼錯在這裏(超出此庫,並在其上下文「域」的概念缺乏經驗)。

上午我做一個簡單的錯誤?或者我有一個根本的缺陷在我的這個垃圾是如何工作的?

感謝理解!

+0

如果我理解模塊尋找的.mo結尾的文件,而不是的.po – deinonychusaur 2012-03-22 20:31:27

回答

6

我對這個非常生疏,但根據以往的經驗和http://docs.python.org/library/gettext,我可以看到兩個主要的東西在這裏失蹤:

  1. LDIR應設置爲包含語言環境數據的基本目錄(在/ usr /共享/區域設置是經典的系統位置)。 gettext將搜索ldir/lang_COUNTRY/catalog.mo
  2. .po文件無法自行讀取,您需要將它們轉換爲.mo二進制文件。通常你會使用msgfmt來做到這一點(mac上的「brew install gettext」是最簡單的方法)。

一個簡單的例子:

$ find /tmp/locales -type f 
/tmp/locales/de_DE/LC_MESSAGES/default.mo 
/tmp/locales/de_DE/LC_MESSAGES/default.po 
/tmp/locales/default.pot 
/tmp/locales/en_IE/LC_MESSAGES/default.mo 
/tmp/locales/en_IE/LC_MESSAGES/default.po 

$ ~/Library/homebrew/Cellar/gettext/0.18.1.1/bin/msgfmt \ 
-o locales/en_IE/LC_MESSAGES/default.mo \ 
locales/en_IE/LC_MESSAGES/default.po 

$ cat /tmp/app.py 
import gettext 
t = gettext.translation('default', "/tmp/locales") 
_ = t.ugettext 

print _("Hello World") 

$ locale 
LANG="en_IE.UTF-8" 
LC_COLLATE="en_IE.UTF-8" 
LC_CTYPE="en_IE.UTF-8" 
LC_MESSAGES="en_IE.UTF-8" 
LC_MONETARY="en_IE.UTF-8" 
LC_NUMERIC="en_IE.UTF-8" 
LC_TIME="en_IE.UTF-8" 
LC_ALL= 

$ python app.py 
How's the craic? 

$ LC_MESSAGES=de_DE python app.py 
Guten Tag