本文整理汇总了Python中babel.messages.Catalog.add方法的典型用法代码示例。如果您正苦于以下问题:Python Catalog.add方法的具体用法?Python Catalog.add怎么用?Python Catalog.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类babel.messages.Catalog
的用法示例。
在下文中一共展示了Catalog.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
# 需要导入模块: from babel.messages import Catalog [as 别名]
# 或者: from babel.messages.Catalog import add [as 别名]
def setUp(self):
# Use a locale which won't fail to run the tests
os.environ['LANG'] = 'en_US.UTF-8'
messages1 = [
('foo', {'string': 'Voh'}),
('foo', {'string': 'VohCTX', 'context': 'foo'}),
(('foo1', 'foos1'), {'string': ('Voh1', 'Vohs1')}),
(('foo1', 'foos1'), {'string': ('VohCTX1', 'VohsCTX1'), 'context': 'foo'}),
]
messages2 = [
('foo', {'string': 'VohD'}),
('foo', {'string': 'VohCTXD', 'context': 'foo'}),
(('foo1', 'foos1'), {'string': ('VohD1', 'VohsD1')}),
(('foo1', 'foos1'), {'string': ('VohCTXD1', 'VohsCTXD1'), 'context': 'foo'}),
]
catalog1 = Catalog(locale='en_GB', domain='messages')
catalog2 = Catalog(locale='en_GB', domain='messages1')
for ids, kwargs in messages1:
catalog1.add(ids, **kwargs)
for ids, kwargs in messages2:
catalog2.add(ids, **kwargs)
catalog1_fp = BytesIO()
catalog2_fp = BytesIO()
write_mo(catalog1_fp, catalog1)
catalog1_fp.seek(0)
write_mo(catalog2_fp, catalog2)
catalog2_fp.seek(0)
translations1 = support.Translations(catalog1_fp)
translations2 = support.Translations(catalog2_fp, domain='messages1')
self.translations = translations1.add(translations2, merge=False)
示例2: test_translation_plugins
# 需要导入模块: from babel.messages import Catalog [as 别名]
# 或者: from babel.messages.Catalog import add [as 别名]
def test_translation_plugins(app, tmpdir):
session.lang = 'fr_FR'
plugin = MockPlugin(plugin_engine, app)
app.extensions['pluginengine'].plugins['dummy'] = plugin
plugin.root_path = tmpdir.strpath
french_core_str = DICTIONARIES['fr_FR']['This is not a string']
french_plugin_str = "This is not le french string"
trans_dir = os.path.join(plugin.root_path, 'translations', 'fr_FR', 'LC_MESSAGES')
os.makedirs(trans_dir)
# Create proper *.mo file for plugin translation
with open(os.path.join(trans_dir, 'messages.mo'), 'wb') as f:
catalog = Catalog(locale='fr_FR', domain='plugin')
catalog.add("This is not a string", "This is not le french string")
write_mo(f, catalog)
gettext_plugin = make_bound_gettext('dummy')
assert _(u'This is not a string') == french_core_str
assert gettext_context(u"This is not a string") == french_core_str
assert gettext_plugin(u"This is not a string") == french_plugin_str
with plugin.plugin_context():
assert _(u'This is not a string') == french_core_str
assert gettext_context(u"This is not a string") == french_plugin_str
assert gettext_plugin(u"This is not a string") == french_plugin_str
示例3: test_sorting
# 需要导入模块: from babel.messages import Catalog [as 别名]
# 或者: from babel.messages.Catalog import add [as 别名]
def test_sorting(self):
# Ensure the header is sorted to the first entry so that its charset
# can be applied to all subsequent messages by GNUTranslations
# (ensuring all messages are safely converted to unicode)
catalog = Catalog(locale='en_US')
catalog.add(u'', '''\
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n''')
catalog.add(u'foo', 'Voh')
catalog.add((u'There is', u'There are'), (u'Es gibt', u'Es gibt'))
catalog.add(u'Fizz', '')
catalog.add(('Fuzz', 'Fuzzes'), ('', ''))
buf = StringIO()
mofile.write_mo(buf, catalog)
buf.seek(0)
translations = gettext.GNUTranslations(fp=buf)
self.assertEqual(u'Voh', translations.ugettext('foo'))
assert isinstance(translations.ugettext('foo'), unicode)
self.assertEqual(u'Es gibt', translations.ungettext('There is', 'There are', 1))
assert isinstance(translations.ungettext('There is', 'There are', 1), unicode)
self.assertEqual(u'Fizz', translations.ugettext('Fizz'))
assert isinstance(translations.ugettext('Fizz'), unicode)
self.assertEqual(u'Fuzz', translations.ugettext('Fuzz'))
assert isinstance(translations.ugettext('Fuzz'), unicode)
self.assertEqual(u'Fuzzes', translations.ugettext('Fuzzes'))
assert isinstance(translations.ugettext('Fuzzes'), unicode)
示例4: test_sorting
# 需要导入模块: from babel.messages import Catalog [as 别名]
# 或者: from babel.messages.Catalog import add [as 别名]
def test_sorting(self):
# Ensure the header is sorted to the first entry so that its charset
# can be applied to all subsequent messages by GNUTranslations
# (ensuring all messages are safely converted to unicode)
catalog = Catalog(locale="en_US")
catalog.add(
u"",
"""\
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n""",
)
catalog.add(u"foo", "Voh")
catalog.add((u"There is", u"There are"), (u"Es gibt", u"Es gibt"))
catalog.add(u"Fizz", "")
catalog.add(("Fuzz", "Fuzzes"), ("", ""))
buf = StringIO()
mofile.write_mo(buf, catalog)
buf.seek(0)
translations = gettext.GNUTranslations(fp=buf)
self.assertEqual(u"Voh", translations.ugettext("foo"))
assert isinstance(translations.ugettext("foo"), unicode)
self.assertEqual(u"Es gibt", translations.ungettext("There is", "There are", 1))
assert isinstance(translations.ungettext("There is", "There are", 1), unicode)
self.assertEqual(u"Fizz", translations.ugettext("Fizz"))
assert isinstance(translations.ugettext("Fizz"), unicode)
self.assertEqual(u"Fuzz", translations.ugettext("Fuzz"))
assert isinstance(translations.ugettext("Fuzz"), unicode)
self.assertEqual(u"Fuzzes", translations.ugettext("Fuzzes"))
assert isinstance(translations.ugettext("Fuzzes"), unicode)
示例5: test_multiple_pos
# 需要导入模块: from babel.messages import Catalog [as 别名]
# 或者: from babel.messages.Catalog import add [as 别名]
def test_multiple_pos(self):
"""If the language writes to multiple .po files, those are
all counted together. Either all of them will be written,
or none of them will be.
"""
p = self.setup_project()
p.write_xml(kind='strings')
p.write_xml(kind='arrays')
# Create two catalogs, one fully translated, the other one not
# at all.
c = Catalog(locale='de')
c.add('translated', 'value', context='translated')
p.write_po(c, 'strings-de.po')
c = Catalog(locale='de')
c.add('untranslated', context='untranslated')
p.write_po(c, 'arrays-de.po')
# If we require 100% completness on import, both files will
# be empty, even though one of them is fully translated. But
# the second drags down the total of the group.
p.program('import', {'--require-min-complete': '1'})
assert len(p.get_xml('de', kind='strings')) == 0
assert len(p.get_xml('de', kind='arrays')) == 0
示例6: convert_xlsm_content
# 需要导入模块: from babel.messages import Catalog [as 别名]
# 或者: from babel.messages.Catalog import add [as 别名]
def convert_xlsm_content(contents):
catalog = Catalog()
for content in contents:
resid = content[0]
res_org_content = content[1]
rescontent = content[2]
if resid == None:
continue
if rescontent == None:
rescontent = u""
if match(r"\((.+)(::(.+))+\)", res_org_content):
msg_id = res_org_content[1:-1].split("::")
msg_string = rescontent[1:-1].split("::")
catalog.add(msg_id, context=resid, string=msg_string)
else:
if match(r"\".+\"", res_org_content):
res_org_content = res_org_content[1:-1]
if match(r"\".+\"", rescontent):
rescontent = rescontent[1:-1]
catalog.add(res_org_content, context=resid, string=rescontent)
return catalog
示例7: assert_convert
# 需要导入模块: from babel.messages import Catalog [as 别名]
# 或者: from babel.messages.Catalog import add [as 别名]
def assert_convert(cls, po, xml=None, namespaces={}):
"""Helper that passes the string in ``po`` through our po
to xml converter, and checks the resulting xml string value
against ``xml``.
If ``xml`` is not given, we check against ``po`` instead, i.e.
expect the string to remain unchanged.
"""
key = 'test'
catalog = Catalog()
catalog.add(po, po, context=key)
warnfunc = TestWarnFunc()
dom = write_xml(po2xml(catalog, warnfunc=warnfunc), warnfunc=warnfunc)
elem = dom.xpath('/resources/string[@name="%s"]' % key)[0]
elem_as_text = etree.tostring(elem, encoding=unicode)
value = re.match("^[^>]+>(.*)<[^<]+$", elem_as_text).groups(1)[0]
match = xml if xml is not None else po
print "'%s' == '%s'" % (value, match)
print repr(value), '==', repr(match)
assert value == match
# If ``namespaces`` are set, the test expects those to be defined
# in the root of the document
for prefix, uri in namespaces.items():
assert dom.nsmap[prefix] == uri
# In this case, the reverse (converting back to po) always needs to
# give us the original again, so this allows for a nice extra check.
if not match: # Skip this if we are doing a special, custom match.
TestFromXML.assert_convert(match, po, namespaces)
return warnfunc
示例8: _extract
# 需要导入模块: from babel.messages import Catalog [as 别名]
# 或者: from babel.messages.Catalog import add [as 别名]
def _extract(self, app):
catalog = Catalog(domain="django", charset="utf8")
files = {}
for dirpath, dirnames, filenames in filtered_walk(app.path):
for filename in filenames:
filename = os.path.join(dirpath, filename)
if ACCEPTABLE_FILENAMES_RE.match(filename):
rel_filename = filename[len(os.path.commonprefix((app.path, filename))) + 1:].replace(os.sep, "/")
files[rel_filename] = filename
self.log.info("%s: %d translatable files found", app.label, len(files))
extractors = self.get_extractors()
for rel_filename, filename in sorted(files.items()):
extractor_tup = extractors.get(os.path.splitext(filename)[1])
if not extractor_tup:
self.log.warning("Not sure how to extract messages from %s", filename)
continue
extractor, options = extractor_tup
with open(filename, "rb") as fp:
for (lineno, message, comments, context) in extract(extractor, fp, options=options):
catalog.add(message, locations=[(rel_filename, 0)], auto_comments=comments)
if len(catalog):
pot_path = self._get_pot_path(app)
with open(pot_path, "w") as outf:
pofile.write_po(outf, catalog, width=1000, omit_header=True, sort_output=True)
self.log.info("%s: %d messages in %s", app.label, len(catalog), pot_path)
return catalog
示例9: extract_messages
# 需要导入模块: from babel.messages import Catalog [as 别名]
# 或者: from babel.messages.Catalog import add [as 别名]
def extract_messages(dirs):
catalog = Catalog(
project='Open Library',
copyright_holder='Internet Archive'
)
METHODS = [
("**.py", "python"),
("**.html", "openlibrary.i18n:extract_templetor")
]
COMMENT_TAGS = ["NOTE:"]
for d in dirs:
if '.html' in d:
extracted = [(d,) + extract for extract in extract_from_file("openlibrary.i18n:extract_templetor", d)]
else:
extracted = extract_from_dir(d, METHODS, comment_tags=COMMENT_TAGS, strip_comment_tags=True)
for filename, lineno, message, comments, context in extracted:
catalog.add(message, None, [(filename, lineno)], auto_comments=comments)
path = os.path.join(root, 'messages.pot')
f = open(path, 'w')
write_po(f, catalog)
f.close()
print('wrote template to', path)
示例10: mkcatalog
# 需要导入模块: from babel.messages import Catalog [as 别名]
# 或者: from babel.messages.Catalog import add [as 别名]
def mkcatalog(locale='de'):
"""Helper that returns a gettext catalog with one message
already added.
Tests can add a broken message and then ensure that at least
the valid message still was processed.
"""
c = Catalog(locale='de')
c.add('valid_message', 'valid_value', context='valid_message')
return c
示例11: test
# 需要导入模块: from babel.messages import Catalog [as 别名]
# 或者: from babel.messages.Catalog import add [as 别名]
def test(self):
p = self.setup_project()
c = Catalog(locale='de')
c.add('en1', 'de1', flags=('fuzzy',), context='foo')
c.add('en2', 'de2', context='bar')
p.write_po(c, 'de.po')
p.program('import', {'--ignore-fuzzy': True})
xml = p.get_xml('de')
assert not 'foo' in xml
assert 'bar' in xml
示例12: test_invalid_xhtml
# 需要导入模块: from babel.messages import Catalog [as 别名]
# 或者: from babel.messages.Catalog import add [as 别名]
def test_invalid_xhtml():
"""Ensure we can deal with broken XML in messages.
"""
c = Catalog()
c.add('Foo', '<i>Tag is not closed', context="foo")
# [bug] This caused an exception in 16263b.
dom = write_xml(po2xml(c))
# The tag was closed automatically (our loose parser tries to fix errors).
assert etree.tostring(dom) == b'<resources><string name="foo"><i>Tag is not closed</i></string></resources>'
示例13: test_load
# 需要导入模块: from babel.messages import Catalog [as 别名]
# 或者: from babel.messages.Catalog import add [as 别名]
def test_load(self):
tempdir = tempfile.mkdtemp()
try:
messages_dir = os.path.join(tempdir, 'fr', 'LC_MESSAGES')
os.makedirs(messages_dir)
catalog = Catalog(locale='fr', domain='messages')
catalog.add('foo', 'bar')
write_mo(file(os.path.join(messages_dir, 'messages.mo'), 'wb'), catalog)
translations = support.Translations.load(tempdir, locales=('fr',), domain='messages')
self.assertEqual('bar', translations.gettext('foo'))
finally:
shutil.rmtree(tempdir)
示例14: test_load
# 需要导入模块: from babel.messages import Catalog [as 别名]
# 或者: from babel.messages.Catalog import add [as 别名]
def test_load(self):
tempdir = tempfile.mkdtemp()
try:
messages_dir = os.path.join(tempdir, "fr", "LC_MESSAGES")
os.makedirs(messages_dir)
catalog = Catalog(locale="fr", domain="messages")
catalog.add("foo", "bar")
with open(os.path.join(messages_dir, "messages.mo"), "wb") as f:
write_mo(f, catalog)
translations = support.Translations.load(tempdir, locales=("fr",), domain="messages")
self.assertEqual("bar", translations.gettext("foo"))
finally:
shutil.rmtree(tempdir)
示例15: test_untranslated
# 需要导入模块: from babel.messages import Catalog [as 别名]
# 或者: from babel.messages.Catalog import add [as 别名]
def test_untranslated():
"""Test that by default, untranslated strings are not included in the
imported XML.
"""
catalog = Catalog()
catalog.add('green', context='color1')
catalog.add('red', 'rot', context='color2')
assert po2xml(catalog) == {'color2': 'rot'}
# If with_untranslated is passed, then all strings are included.
# Note that arrays behave differently (they always include all
# strings), and this is tested in test_string_arrays.py).
assert po2xml(catalog, with_untranslated=True) ==\
{'color1': 'green', 'color2': 'rot'}