【发布时间】:2017-01-25 09:43:36
【问题描述】:
我想知道是否可以在运行时检查gettext中是否存在要翻译的字符串。
仅用于调试目的。
有时要翻译的字符串会稍微更新,没有人会考虑更新 po 文件。错误一直存在,直到有人发现它或出于其他原因决定更新 po 文件。
如果有更好的方法来处理这个案例,我也很感兴趣。
【问题讨论】:
我想知道是否可以在运行时检查gettext中是否存在要翻译的字符串。
仅用于调试目的。
有时要翻译的字符串会稍微更新,没有人会考虑更新 po 文件。错误一直存在,直到有人发现它或出于其他原因决定更新 po 文件。
如果有更好的方法来处理这个案例,我也很感兴趣。
【问题讨论】:
这有点hacky,但它有效吗? 我将翻译类的后备设置为自定义类,当找不到翻译时通知我们。不确定您的设置是什么,但其中的一些变体应该可以工作,对吧?
# translate.py
import gettext
import os.path
missed_translations = set()
class MyFallback(gettext.NullTranslations):
def gettext(self, msg):
# do whatever you want to do when no translation found
# like log a message, or email someone, or raise an exception
missed_translations.add(msg)
return msg
class MyTranslations(gettext.GNUTranslations, object):
def __init__(self, *args, **kwargs):
super(MyTranslations, self).__init__(*args, **kwargs)
self.add_fallback(MyFallback())
lang1 = gettext.translation(
"translate",
localedir=os.path.expanduser("~/Projects/translate/locale"),
languages=["es"],
class_=MyTranslations
)
lang1.install()
print(_("Hello World"))
print(_("Hello world"))
print(_("nope"))
print("Missing translations for: " + ", ".join(missed_translations))
如果你想重现我的目录结构:
├── __init__.py
├── locale
│ ├── es
│ │ └── LC_MESSAGES
│ │ └── translate.mo
│ └── messages-es_ES.po
└── translate.py
运行起来是这样的:
$> python translate.py
Hola Mundo
Hello world
nope
Missing translations for: nope, Hello world
【讨论】: