使用Jinja2和Pyramid在i18n上使用Python。似乎有一个问题,知道它应该如何翻译%%。 我开始怀疑这个bug是在Jinja2中。
所以我做了一些调查,看起来问题更多的是gettext而不是jinja2,如repl所示
>>>gettext.gettext("98%% off %s sale") % ('holiday')
'98% off holiday sale'
>>>gettext.gettext("98%% off sale")
'98%% off sale'
>>>gettext.gettext("98% off %s sale") % ('holiday')
Traceback (most recent call last):
Python Shell, prompt 13, line 1
TypeError: %o format: a number is required, not str
这似乎是鸡/蛋的问题。
所有这些意味着翻译人员(大多数不是计算机程序员)必须非常小心他们如何进行翻译,每个人都需要非常小心包含%的翻译。
似乎我们这样做是错误的(不知何故)并且应该有一个更直接和统一的格式来做这件事。现在我们只是通过简单地注入一个%作为格式参数来应对。
有没有更好的方法来做到这一点,还是这样做得好?
底部有一个.po文件
单元测试几乎说明了一切,为什么最后一个断言失败了?这是Jinja2的错误,还是我需要以不同的方式解决这个问题。
class Jinja2Tests(TestCase):
def test_percent_percent(self):
""" i18n(gettext) expresses 98% as 98%% only in some versions of jinja2 that has not
worked as expected. This is to make sure that it is working. """
env = Environment(extensions=['jinja2.ext.i18n'])
lang = gettext.translation('messages', path.abspath(path.join(path.dirname(__file__), 'data')))
env.install_gettext_translations(lang)
template = env.from_string(source="{{ _('98%% off %(name)s sale') | format(name='holiday') }}")
result = template.render()
self.assertEqual('98% off holiday sale(translated)', result)
template = env.from_string(source="{{ _('98%% off sale') }}")
result = template.render()
# THE LINE BELOW FAILS WITH:
# AssertionError: '98% off sale(translated)' != u'98%% off sale(translated)'
self.assertEqual('98% off sale(translated)', result)
要将MO文件编译为PO文件以运行上述代码。
# This file is distributed under the same license as the Uniregistrar project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2016.
#
msgid ""
msgstr ""
"Project-Id-Version: Uniregistrar 1.0\n"
"Report-Msgid-Bugs-To: mark@uniregistry.com\n"
"POT-Creation-Date: 2016-12-22 15:22-0500\n"
"PO-Revision-Date: 2016-11-14 16:42-0500\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language: en\n"
"Language-Team: en <LL@li.org>\n"
"Plural-Forms: nplurals=2; plural=(n != 1)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.3.3\n"
#: uniregistrar/constants.py:90
msgid "98%% off sale"
msgstr "98%% off sale(translated)"
#: uniregistrar/constants.py:90
msgid "98%% off %(name)s sale"
msgstr "98%% off %(name)s sale(translated)"