Beispiel #1
0
def _localize_timezones(locale: babel.Locale) -> LocalizedTimezone:
    zones_and_aliases = _read_timezone_ids_and_aliases()
    # locale.language: 'en' or 'en_US'
    collator = Collator.createInstance(Locale.createFromName(locale.language))
    return [
        _localize_timezone(zone, aliases, locale, collator)
        for zone, aliases in zones_and_aliases.items()
    ]
Beispiel #2
0
def divideIntoWords(txt, locale):
    loc = Locale.createFromName(locale)
    bi = BreakIterator.createWordInstance(loc)
    #print txt
    bi.setText(txt)
    res = []
    while True:
        try:
            #print bi.next()
            res.append(bi.next())
        except StopIteration:
            return res
Beispiel #3
0
def icu_format_message(locale_id: str,
                       message: str,
                       arguments: _MessageArguments = {}) -> str:
    """Substitute arguments into ICU-style message.
    You can have variable substitution, plurals, selects and nested messages.
    
    Raises `ICUError` in case of incorrectly formatted message.
    
    The arguments must be a dict
    """
    return MessageFormat(message, Locale.createFromName(locale_id)).format(
        list(arguments.keys()), [Formattable(x) for x in arguments.values()])
Beispiel #4
0
 def endElement(self, name):
     if name == u"Unicode":
         self.__isUni = False
         loc = Locale.createFromName("utf-8")
         bi = BreakIterator.createWordInstance(loc)
         bi.setText(self.__uniText)
         tokens = []
         prev = 0
         while True:
             try:
                 ind = bi.next()
                 tokens.append(self.__uniText[prev:ind])
                 prev = ind
             except StopIteration:
                 break
         text = u""
         for t in tokens:
             text += processToken(t)
         self.__downstream.characters(text)
     self.__downstream.endElement(name)
Beispiel #5
0
	def endElement(self, name):
		if name == u"Unicode":
			self.__isUni = False
			loc = Locale.createFromName("utf-8")
			bi = BreakIterator.createWordInstance(loc)
			bi.setText(self.__uniText)
			tokens = []
			prev = 0
			while True:
				try:
					ind = bi.next()
					tokens.append(self.__uniText[prev:ind])
					prev = ind
				except StopIteration:
					break
			text = u""
			for t in tokens:
				text += processToken(t)
			self.__downstream.characters(text)
		self.__downstream.endElement(name)
Beispiel #6
0
def icu_format_html_message(
    locale_id: str,
    message: str,
    arguments: _MessageArguments = {},
    tags: _TagMapping = {},
) -> str:
    """Substitute arguments into ICU-style HTML message.
    You can have variable substitution, plurals, selects and nested messages.
    You can also replace HTML tag placeholders.
    
    Raises `ICUError` in case of incorrectly formatted message.
    """
    return MessageFormat(restore_tags(
        message, tags), Locale.createFromName(locale_id)).format(
            list(arguments.keys()),
            [
                Formattable(escape(x) if isinstance(x, str) else x)
                for x in arguments.values()
            ],
        )
Beispiel #7
0
def make_collator(request):
    loc = Locale.createFromName(request.locale_name)
    return Collator.createInstance(loc)
Beispiel #8
0
 def __init__(self):
     self.BreakIterator = BreakIterator.createWordInstance(
         Locale.createFromName('ar'))
Beispiel #9
0
    def __init__(self, localedir=None, lang=None, domain=None, languages=None):
        """
        Init a GrampsLocale. Run __init_first_instance() to set up the
        environment if this is the first run. Return __first_instance
        otherwise if called without arguments.
        """
        global _hdlr
        #initialized is special, used only for the "first instance",
        #and created by __new__(). It's used to prevent re-__init__ing
        #__first_instance when __new__() returns its pointer.
        if hasattr(self, 'initialized') and self.initialized:
            return
        _first = self._GrampsLocale__first_instance
        self.localedir = None
        # Everything breaks without localedir, so get that set up
        # first.  Warnings are logged in _init_first_instance or
        # _init_secondary_locale if this comes up empty.
        if localedir and os.path.exists(os.path.abspath(localedir)):
            self.localedir = localedir
        elif (_first and hasattr(_first, 'localedir') and _first.localedir
              and os.path.exists(os.path.abspath(_first.localedir))):
            self.localedir = _first.localedir
        else:
            LOG.warning(
                'Missing or invalid localedir %s; no translations'
                ' will be available.', repr(localedir))
        self.lang = lang
        self.localedomain = domain or 'gramps'
        if languages:
            self.language = [
                x for x in [
                    self.check_available_translations(l)
                    for l in languages.split(":")
                ] if x
            ]
        else:
            self.language = None

        if self == _first:
            self._GrampsLocale__init_first_instance()
        else:
            self._init_secondary_locale()

        self.icu_locales = {}
        self.collator = None
        if HAVE_ICU:
            self.icu_locales["default"] = Locale.createFromName(self.lang)
            if self.collation and self.collation != self.lang:
                self.icu_locales["collation"] = Locale.createFromName(
                    self.collation)
            else:
                self.icu_locales["collation"] = self.icu_locales["default"]
            try:
                self.collator = Collator.createInstance(
                    self.icu_locales["collation"])
            except ICUError as err:
                LOG.warning("Unable to create collator: %s", str(err))
                self.collator = None

        try:
            self.translation = self._get_translation(self.localedomain,
                                                     self.localedir,
                                                     self.language)
        except ValueError:
            LOG.warning(
                "Unable to find translation for languages in %s, using US English",
                ':'.join(self.language))
            self.translation = GrampsNullTranslations()
            self.translation._language = "en"

        if _hdlr:
            LOG.removeHandler(_hdlr)
            _hdlr = None
        self._dd = self._dp = None
        #Guards against running twice on the first instance.
        self.initialized = True
Beispiel #10
0
    def __init__(self, localedir=None, lang=None, domain=None, languages=None):
        """
        Init a WearNowLocale. Run __init_first_instance() to set up the
        environment if this is the first run. Return __first_instance
        otherwise if called without arguments.
        """
        global _hdlr
        #initialized is special, used only for the "first instance",
        #and created by __new__(). It's used to prevent re-__init__ing
        #__first_instance when __new__() returns its pointer.
        if hasattr(self, 'initialized') and self.initialized:
            return
        _first = self._WearNowLocale__first_instance
        self.localedir = None
        # Everything breaks without localedir, so get that set up
        # first.  Warnings are logged in _init_first_instance or
        # _init_secondary_locale if this comes up empty.
        if localedir and os.path.exists(os.path.abspath(localedir)):
            self.localedir = localedir
        elif (_first and hasattr(_first, 'localedir') and _first.localedir and
              os.path.exists(os.path.abspath(_first.localedir))):
            self.localedir = _first.localedir
        else:
            LOG.warn('Missing or invalid localedir %s; no translations will be available.', repr(localedir))

        self.lang = lang
        self.localedomain = domain or 'wearnow'
        if languages:
            self.language = [x for x in [self.check_available_translations(l)
                                         for l in languages.split(":")]
                             if x]
        else:
            self.language = None

        if self == _first:
            self._WearNowLocale__init_first_instance()
        else:
            self._init_secondary_locale()

        self.icu_locales = {}
        self.collator = None
        if HAVE_ICU:
            self.icu_locales["default"] = Locale.createFromName(self.lang)
            if self.collation and self.collation != self.lang:
                self.icu_locales["collation"] = Locale.createFromName(self.collation)
            else:
                self.icu_locales["collation"] = self.icu_locales["default"]
            try:
                self.collator = Collator.createInstance(self.icu_locales["collation"])
            except ICUError as err:
                LOG.warning("Unable to create collator: %s", str(err))
                self.collator = None

        try:
            self.translation = self._get_translation(self.localedomain,
                                                     self.localedir,
                                                     self.language)
        except ValueError:
            LOG.warning("Unable to find translation for languages in %s, using US English", ':'.join(self.language))
            self.translation = WearNowNullTranslations()
            self.translation._language = "en"

        if _hdlr:
            LOG.removeHandler(_hdlr)
            _hdlr = None
        self._dd = self._dp = None
        #Guards against running twice on the first instance.
        self.initialized = True
Beispiel #11
0
 def __init__(self):
     self.BreakIterator = BreakIterator.createWordInstance(
                                               Locale.createFromName('ar'))
Beispiel #12
0
 def __init__(self, locale_id: str, catalog: Catalog):
     self.icu_locale = Locale.createFromName(locale_id)
     self.catalog = catalog