使用gettext的Python i18n无效

时间:2017-09-24 21:08:18

标签: python python-3.x internationalization gettext

我试着看一下关于在python项目上制作一些i18n机制的python文档。虽然我通常喜欢python docs,但这部分看起来并不直观,而且我看了另外一些资源。看看这些:

inventwithpython.com/blog/translate-your-python-3-program-with-the-gettext-module/

Python docs: localizing-your-application

我设法完成了下面粘贴的源代码。首先它是一个域错误,但在添加.mo文件后,现在它不起作用或显示任何错误。

main.py

from gettext import translation
from gettext import gettext as _

lang1 = translation('poker', '/home/myUser/myProjects/pokerProject/resources/localedir', languages=['en'])
lang2 = translation('poker', '/home/myUser/myProjects/pokerProject/resources/localedir', languages=['es'])

lang2.install()

# Code with strings in this way 
print(_('This should be translated'))

.mo文件示例

"Generated-By: pygettext.py 1.5\n"
"X-Generator: Poedit 2.0.1\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: main.py:26
msgid "This should be translated"
msgstr "Translated text"

布局(pokerProject子树)

.
├── martintc
│   ├── __init__.py
│   └── poker
│       ├── __init__.py
│       └── model
│           ├── diceset.py
│           ├── die.py
│           ├── errors.py
│           ├── __init__.py
│           ├── main.py
│           ├── poker.pot
│           └── utils.py
└── resources
    └── localedir
        ├── en
        │   └── LC_MESSAGES
        │       ├── poker.mo
        │       └── poker.po
        └── es
            └── LC_MESSAGES
                ├── poker.mo
                └── poker.po

1 个答案:

答案 0 :(得分:0)

我发现了问题并且是一个临时但不令人满意的解决方案。

我的代码有一行:

from gettext import gettext as _

并不需要它。事实上,当我删除这一行时,一切都很顺利。

我不明白为什么,但这解决了它。我不知道当我有另一个带有i18n字符串的类

时这是否会起作用