我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用gettext.GNUTranslations()。
def __init__(self, language): """Create a GNUTranslations() using many locale directories""" gettext_module.GNUTranslations.__init__(self) self.set_output_charset('utf-8') # For Python 2 gettext() (#25720) self.__language = language self.__to_language = to_language(language) self.__locale = to_locale(language) self._catalog = None self._init_translation_catalog() self._add_installed_apps_translations() self._add_local_translations() if self.__language == settings.LANGUAGE_CODE and self._catalog is None: # default lang should have at least one translation file available. raise IOError("No translation files found for default language %s." % settings.LANGUAGE_CODE) self._add_fallback() if self._catalog is None: # No catalogs found for this language, set an empty catalog. self._catalog = {}
def ngettext(self, singular, plural, num): """ The translation of singular/plural is returned unless the translation is not available and the singular contains the separator. In that case, the returned value is the singular. :param singular: The singular form of the string to be translated. may contain a context seperator :type singular: unicode :param plural: The plural form of the string to be translated. :type plural: unicode :param num: the amount for which to decide the translation :type num: int :returns: Translation or the original. :rtype: unicode """ return gettext.GNUTranslations.ngettext(self, singular, plural, num)
def gettext_for(lang): """ Return a GNUTranslation class for the given language. Example: >>> trans = gettext_for('pt_BR') >>> _ = trans.gettext >>> _('hello world!') # doctest: +SKIP 'olá mundo!' """ lang = lang.replace('-', '_') try: with open(os.path.join(L10N_PATH, lang + '.mo'), 'rb') as F: result = gettext.GNUTranslations(F) except FileNotFoundError: result = gettext.NullTranslations() return result
def test_the_alternative_interface(self): eq = self.assertEqual # test the alternative interface with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) # Install the translation object t.install() eq(_('nudge nudge'), 'wink wink') # Try unicode return type t.install() eq(_('mullusk'), 'bacon') # Test installation of other methods import builtins t.install(names=["gettext", "lgettext"]) eq(_, t.gettext) eq(builtins.gettext, t.gettext) eq(lgettext, t.lgettext) del builtins.gettext del builtins.lgettext
def test_the_alternative_interface(self): eq = self.assertEqual # test the alternative interface with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) # Install the translation object t.install() eq(_('nudge nudge'), 'wink wink') # Try unicode return type t.install(unicode=True) eq(_('mullusk'), 'bacon') # Test installation of other methods import __builtin__ t.install(unicode=True, names=["gettext", "lgettext"]) eq(_, t.ugettext) eq(__builtin__.gettext, t.ugettext) eq(lgettext, t.lgettext) del __builtin__.gettext del __builtin__.lgettext
def _setup_locale(): """ Setting up localization :return: translation method """ try: locale_file = Config.get('xpopup', 'locale_file') except: from os.path import abspath, dirname, join locale_file = join(dirname(abspath(__file__)), 'xpopup.mo') try: with open(locale_file, "rb") as f: xpopup_locale = gettext.GNUTranslations(f) Logger.info('Localization file loaded (%s).' % locale_file) except Exception as e: Logger.warning('%s: %s. Switch to the defaults.' % (e.__class__.__name__, str(e))) xpopup_locale = gettext.NullTranslations() if PY2: return xpopup_locale.ugettext else: return xpopup_locale.gettext
def _new_gnu_trans(self, localedir, use_null_fallback=True): """ Returns a mergeable gettext.GNUTranslations instance. A convenience wrapper. By default gettext uses 'fallback=False'. Using param `use_null_fallback` to avoid confusion with any other references to 'fallback'. """ translation = gettext_module.translation( domain='django', localedir=localedir, languages=[self.__locale], codeset='utf-8', fallback=use_null_fallback) if not hasattr(translation, '_catalog'): # provides merge support for NullTranslations() translation._catalog = {} translation._info = {} translation.plural = lambda n: int(n != 1) return translation
def merge(self, translations): """Merge the given translations into the catalog. Message translations in the specified catalog override any messages with the same identifier in the existing catalog. :param translations: the `Translations` instance with the messages to merge """ if isinstance(translations, gettext.GNUTranslations): self._catalog.update(translations._catalog) if isinstance(translations, Translations): self.files.extend(translations.files) return self
def _new_gnu_trans(self, localedir, use_null_fallback=True): """ Returns a mergeable gettext.GNUTranslations instance. A convenience wrapper. By default gettext uses 'fallback=False'. Using param `use_null_fallback` to avoid confusion with any other references to 'fallback'. """ return gettext_module.translation( domain='django', localedir=localedir, languages=[self.__locale], codeset='utf-8', fallback=use_null_fallback)
def _add_fallback(self): """Sets the GNUTranslations() fallback with the default language.""" # Don't set a fallback for the default language or any English variant # (as it's empty, so it'll ALWAYS fall back to the default language) if self.__language == settings.LANGUAGE_CODE or self.__language.startswith('en'): return default_translation = translation(settings.LANGUAGE_CODE) self.add_fallback(default_translation)
def get_builtin_gnu_translations(languages=None): """ Get a gettext.GNUTranslations object pointing at the included translation files. :param languages: A list of languages to try, in order. If omitted or None, then gettext will try to use locale information from the environment. """ import gettext return gettext.translation('wtforms', messages_path(), languages)
def __init__(self, locale_code): """ Initialize GetText :param locale_code selected locale """ try: filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'locale', '{}.mo'.format(locale_code)) trans = gettext.GNUTranslations(open(filename, "rb")) logger.debug('{} Loaded'.format(filename)) except IOError: logger.debug('Failed to found locale {}'.format(locale_code)) trans = gettext.NullTranslations() trans.install()
def gettext(self, msgid): """ Obtain translation of gettext, return a unicode object :param msgid: The string to translated. :type msgid: unicode :returns: Translation or the original. :rtype: unicode """ # If msgid =="" then gettext will return po file header # and that's not what we want. if len(msgid.strip()) == 0: return msgid return gettext.GNUTranslations.gettext(self, msgid)
def get_translations(languages=None): """ Get a WTForms translation object which wraps the builtin GNUTranslations object. """ translations = get_builtin_gnu_translations(languages) if hasattr(translations, 'ugettext'): return DefaultTranslations(translations) else: # Python 3 has no ugettext/ungettext, so just return the translations object. return translations
def test_plural_forms2(self): eq = self.assertEqual with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) x = t.ngettext('There is %s file', 'There are %s files', 1) eq(x, 'Hay %s fichero') x = t.ngettext('There is %s file', 'There are %s files', 2) eq(x, 'Hay %s ficheros')
def setUp(self): GettextBaseTest.setUp(self) with open(UMOFILE, 'rb') as fp: self.t = gettext.GNUTranslations(fp) self._ = self.t.gettext
def setUp(self): GettextBaseTest.setUp(self) with open(MMOFILE, 'rb') as fp: try: self.t = gettext.GNUTranslations(fp) except: self.tearDown() raise
def set_lang(lang): if lang == 'C': __builtin__.__dict__['_'] = nop else: g = gettext.GNUTranslations(open(os.path.join("po", "%s.mo" % lang), 'rb')) __builtin__.__dict__['_'] = g.ugettext
def __init__(self, locale_code): """ Initialize GetText :param locale_code selected locale """ try: filename = os.path.join('/usr/share/harbour-sailcron/python/cron_descriptor/locale', '{}.mo'.format(locale_code)) trans = gettext.GNUTranslations(open(filename, "rb")) logger.debug('{} Loaded'.format(filename)) except IOError: logger.debug('Failed to found locale {}'.format(locale_code)) trans = gettext.NullTranslations() trans.install()
def test_plural_forms2(self): eq = self.assertEqual with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) x = t.ngettext('There is %s file', 'There are %s files', 1) eq(x, 'Hay %s fichero') x = t.ngettext('There is %s file', 'There are %s files', 2) eq(x, 'Hay %s ficheros') # Examples from http://www.gnu.org/software/gettext/manual/gettext.html
def test_plural_form_error_issue17898(self): with open(MOFILE, 'wb') as fp: fp.write(base64.decodestring(GNU_MO_DATA_ISSUE_17898)) with open(MOFILE, 'rb') as fp: # If this runs cleanly, the bug is fixed. t = gettext.GNUTranslations(fp)
def setUp(self): GettextBaseTest.setUp(self) with open(UMOFILE, 'rb') as fp: self.t = gettext.GNUTranslations(fp) self._ = self.t.ugettext