本文整理匯總了Python中polib.pofile方法的典型用法代碼示例。如果您正苦於以下問題:Python polib.pofile方法的具體用法?Python polib.pofile怎麽用?Python polib.pofile使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類polib
的用法示例。
在下文中一共展示了polib.pofile方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: testPOT
# 需要導入模塊: import polib [as 別名]
# 或者: from polib import pofile [as 別名]
def testPOT(potfile):
"""Run all tests against all entries in a POT file.
:param str potfile: The name of a .pot file to test
:return: whether the checks succeeded or not
:rtype: bool
"""
success = True
parsed_pot = polib.pofile(potfile)
for entry in parsed_pot:
if not testString(entry):
success = False
return success
示例2: build_js_translations
# 需要導入模塊: import polib [as 別名]
# 或者: from polib import pofile [as 別名]
def build_js_translations(self):
import polib
import simplejson as json
def create_js(source, lang):
print 'Generating', lang
po = polib.pofile(source)
data = self.po2dict(po, lang)
data = json.dumps(data, sort_keys=True,
ensure_ascii=False, indent=2 * ' ')
out_dir = os.path.abspath(os.path.join(self.ckan_path, 'public',
'base', 'i18n'))
out_file = open(os.path.join(out_dir, '%s.js' % lang), 'w')
out_file.write(data.encode('utf-8'))
out_file.close()
for l in os.listdir(self.i18n_path):
if os.path.isdir(os.path.join(self.i18n_path, l)):
f = os.path.join(self.i18n_path, l, 'LC_MESSAGES', 'ckan.po')
create_js(f, l)
print 'Completed generating JavaScript translations'
示例3: check_po_file
# 需要導入模塊: import polib [as 別名]
# 或者: from polib import pofile [as 別名]
def check_po_file(path):
errors = []
def check_translation(validator, msgid, msgstr):
if not validator(msgid) == validator(msgstr):
errors.append((msgid, msgstr))
po = polib.pofile(path)
for entry in po.translated_entries():
if entry.msgid_plural and entry.msgstr_plural:
for function in (simple_conv_specs, mapping_keys,
replacement_fields):
for key, msgstr in entry.msgstr_plural.iteritems():
if key == '0':
check_translation(function, entry.msgid,
entry.msgstr_plural[key])
else:
check_translation(function, entry.msgid_plural,
entry.msgstr_plural[key])
elif entry.msgstr:
for function in (simple_conv_specs, mapping_keys,
replacement_fields):
check_translation(function, entry.msgid, entry.msgstr)
return errors
示例4: translate_file
# 需要導入模塊: import polib [as 別名]
# 或者: from polib import pofile [as 別名]
def translate_file(self, root, file_name, target_language):
"""
convenience method for translating a pot file
:param root: the absolute path of folder where the file is present
:param file_name: name of the file to be translated (it should be a pot file)
:param target_language: language in which the file needs to be translated
"""
logger.info('filling up translations for locale `{}`'.format(target_language))
po = polib.pofile(os.path.join(root, file_name))
strings = self.get_strings_to_translate(po)
# translate the strings,
# all the translated strings are returned
# in the same order on the same index
# viz. [a, b] -> [trans_a, trans_b]
tl = get_translator()
translated_strings = tl.translate_strings(strings, target_language, 'en', False)
self.update_translations(po, translated_strings)
po.save()
示例5: import_lang
# 需要導入模塊: import polib [as 別名]
# 或者: from polib import pofile [as 別名]
def import_lang(self, lang):
po = polib.pofile(LOCALE_PATH.format(lang=lang))
total = 0
for entry in [e for e in po]:
msgid = entry.msgid
params = {"text_%s" % lang: entry.msgstr}
total += (
self.dbsession.query(HazCat)
.filter(HazCat.general_recommendation == msgid)
.update({"general_recommendation_%s" % lang: entry.msgstr})
)
total += self.dbsession.query(TecRec).filter(TecRec.text == msgid).update(params)
total += (
self.dbsession.query(TecRec)
.filter(TecRec.detail == msgid)
.update({"detail_%s" % lang: entry.msgstr})
)
total += self.dbsession.query(CcRec).filter(CcRec.text == msgid).update(params)
print("[%s] %s strings updated" % (lang, total))
self.dbsession.flush()
示例6: assert_merge_headers
# 需要導入模塊: import polib [as 別名]
# 或者: from polib import pofile [as 別名]
def assert_merge_headers(self, file_path, num_headers):
"""
This is invoked by test_main to ensure that it runs after
calling generate.main().
There should be exactly num_headers merge comment headers
in our merged .po file. This counts them to be sure.
A merge comment looks like this:
# #-#-#-#-# django-partial.po (0.1a) #-#-#-#-#
"""
pof = pofile(file_path)
pattern = re.compile('^#-#-#-#-#', re.M)
match = pattern.findall(pof.header)
self.assertEqual(
len(match),
num_headers,
msg="Found %s (should be %s) merge comments in the header for %s" % (len(match), num_headers, file_path)
)
示例7: make_dummy
# 需要導入模塊: import polib [as 別名]
# 或者: from polib import pofile [as 別名]
def make_dummy(filename, locale, converter):
"""
Takes a source po file, reads it, and writes out a new po file
in :param locale: containing a dummy translation.
"""
if not Path(filename).exists():
raise IOError(u'File does not exist: %r' % filename)
pofile = polib.pofile(filename)
for msg in pofile:
# Some strings are actually formatting strings, don't dummy-ify them,
# or dates will look like "DÀTÉ_TÌMÉ_FÖRMÀT Ⱡ'σ# EST"
if is_format_message(msg):
continue
converter.convert_msg(msg)
pofile.metadata['Language'] = locale
# Apply declaration for English pluralization rules so that ngettext will
# do something reasonable.
pofile.metadata['Plural-Forms'] = 'nplurals=2; plural=(n != 1);'
new_file = new_filename(filename, locale)
new_file.parent.makedirs_p()
pofile.save(new_file)
clean_pofile(new_file)
示例8: test_usability
# 需要導入模塊: import polib [as 別名]
# 或者: from polib import pofile [as 別名]
def test_usability(pofile):
# Use polib to write a mofile
with tempfile.NamedTemporaryFile(mode="w+b") as mofile:
pofile = polib.pofile(pofile)
pofile.save_as_mofile(mofile.name)
# Try to open it
_t = gettext.GNUTranslations(fp=mofile)
示例9: test_msgfmt
# 需要導入模塊: import polib [as 別名]
# 或者: from polib import pofile [as 別名]
def test_msgfmt(pofile):
# Check that the .po file can actually be compiled
with tempfile.NamedTemporaryFile(mode="w+b", suffix=".mo") as mofile:
try:
# Ignore the output on success
subprocess.check_output(["msgfmt", "-c", "--verbose", "-o", mofile.name, pofile],
stderr=subprocess.STDOUT, universal_newlines=True)
except subprocess.CalledProcessError as e:
raise AssertionError("Unable to compile %s: %s" % (pofile, e.output))
示例10: test_percentage
# 需要導入模塊: import polib [as 別名]
# 或者: from polib import pofile [as 別名]
def test_percentage(pofile):
pofile = polib.pofile(pofile)
if pofile.percent_translated() < threshold:
# Issue a warning instead of an exception, since these should probably
# be handled on a case-by-case basis
warnings.warn("amount translated of %d%% below threshold of %d%%" % (pofile.percent_translated(), threshold))
示例11: test_markup
# 需要導入模塊: import polib [as 別名]
# 或者: from polib import pofile [as 別名]
def test_markup(pofile):
po = polib.pofile(pofile)
for entry in po.translated_entries():
if is_markup(entry.msgid):
# If this is a plural, check each of the plural translations
if entry.msgid_plural:
xlations = entry.msgstr_plural
else:
xlations = {None: entry.msgstr}
for plural_id, msgstr in xlations.items():
# Check if the markup is valid at all
try:
# pylint: disable=unescaped-markup
ET.fromstring('<markup>%s</markup>' % msgstr)
except ET.ParseError:
if entry.msgid_plural:
raise AssertionError("Invalid markup translation for %d translation of msgid %s\n%s" %
(plural_id, entry.msgid, msgstr))
else:
raise AssertionError("Invalid markup translation for msgid %s\n%s" %
(entry.msgid, msgstr))
# Check if the markup has the same number and kind of tags
if not markup_match(entry.msgid, msgstr):
if entry.msgid_plural:
raise AssertionError("Markup does not match for %d translation of msgid %s\n%s" %
(plural_id, entry.msgid, msgstr))
else:
raise AssertionError("Markup does not match for msgid %s\n%s" % (entry.msgid, msgstr))
示例12: update_po_files
# 需要導入模塊: import polib [as 別名]
# 或者: from polib import pofile [as 別名]
def update_po_files():
def get_current_msgids():
pot = polib.pofile("locale/en/LC_MESSAGES/django.po")
return {e.msgid for e in pot if not e.fuzzy and not e.obsolete}
# get the current set of msgids
saved_msgids = get_current_msgids()
# re-extract locale files from source code
ignore_paths = ("env/*", "fabric/*", "media/*", "sitestatic/*", "static/*", "node_modules/*")
ignore_args = " ".join([f'--ignore="{p}"' for p in ignore_paths])
cmd(f"python manage.py makemessages -a -e haml,html,txt,py --no-location --no-wrap {ignore_args}")
# get the new set of msgids
actual_msgids = get_current_msgids()
added_msgids = actual_msgids.difference(saved_msgids)
removed_msgids = saved_msgids.difference(actual_msgids)
if DEBUG:
for mid in added_msgids:
print(f" + {repr(mid)}")
for mid in removed_msgids:
print(f" - {repr(mid)}")
# if there are no actual changes to msgids, revert
if not added_msgids and not removed_msgids:
cmd("git checkout -- locale")
示例13: get_translation_percentage
# 需要導入模塊: import polib [as 別名]
# 或者: from polib import pofile [as 別名]
def get_translation_percentage(self, locale_path: str, locale: str) -> int:
# backend stats
po = polib.pofile(self.get_po_filename(locale_path, locale))
not_translated = len(po.untranslated_entries())
total = len(po.translated_entries()) + not_translated
# frontend stats
with open(self.get_json_filename(locale_path, locale)) as reader:
for key, value in ujson.load(reader).items():
total += 1
if value == '':
not_translated += 1
# mobile stats
with open(os.path.join(locale_path, 'mobile_info.json')) as mob:
mobile_info = ujson.load(mob)
try:
info = mobile_info[locale]
except KeyError:
if self.strict:
raise
info = {'total': 0, 'not_translated': 0}
total += info['total']
not_translated += info['not_translated']
return (total - not_translated) * 100 // total
示例14: print_usage
# 需要導入模塊: import polib [as 別名]
# 或者: from polib import pofile [as 別名]
def print_usage():
"""Print usage message and exit."""
print 'Usage: po_to_mo <pofile> (or drag pofile onto executable icon).'
raw_input()
sys.exit(1)
示例15: parseTranslation
# 需要導入模塊: import polib [as 別名]
# 或者: from polib import pofile [as 別名]
def parseTranslation(langCode: str, poFile: str) -> dict:
if langCode not in LOCALES:
raise Exception("Language not installed")
po = polib.pofile(poFile)
result = {}
for entry in po:
result[entry.msgid] = entry.msgstr
return result
# Build the translation one time to prevent them from being generated on each request