• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python localedata.locale_identifiers函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中babel.localedata.locale_identifiers函数的典型用法代码示例。如果您正苦于以下问题:Python locale_identifiers函数的具体用法?Python locale_identifiers怎么用?Python locale_identifiers使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了locale_identifiers函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_unique_ids

def test_unique_ids():
    # Check all locale IDs are uniques.
    all_ids = localedata.locale_identifiers()
    assert len(all_ids) == len(set(all_ids))
    # Check locale IDs don't collide after lower-case normalization.
    lower_case_ids = list(map(methodcaller('lower'), all_ids))
    assert len(lower_case_ids) == len(set(lower_case_ids))
开发者ID:Mabusto,项目名称:babel,代码行数:7,代码来源:test_localedata.py


示例2: pytest_generate_tests

def pytest_generate_tests(metafunc):
    if hasattr(metafunc.function, "pytestmark"):
        for mark in metafunc.function.pytestmark:
            if mark.name == "all_locales":
                from babel.localedata import locale_identifiers
                metafunc.parametrize("locale", list(locale_identifiers()))
                break
开发者ID:python-babel,项目名称:babel,代码行数:7,代码来源:conftest.py


示例3: get_available_languages

def get_available_languages(domain):
    """Lists the available languages for the given translation domain.

    :param domain: the domain to get languages for
    """
    if domain in _AVAILABLE_LANGUAGES:
        return copy.copy(_AVAILABLE_LANGUAGES[domain])

    localedir = os.environ.get(_locale.get_locale_dir_variable_name(domain))
    find = lambda x: gettext.find(domain,
                                  localedir=localedir,
                                  languages=[x])

    # NOTE(mrodden): en_US should always be available (and first in case
    # order matters) since our in-line message strings are en_US
    language_list = ['en_US']
    locale_identifiers = localedata.locale_identifiers()
    language_list.extend(language for language in locale_identifiers
                         if find(language))

    # In Babel 1.3, locale_identifiers() doesn't list some OpenStack supported
    # locales (e.g. 'zh_CN', and 'zh_TW') so we add the locales explicitly if
    # necessary so that they are listed as supported.
    aliases = {'zh': 'zh_CN',
               'zh_Hant_HK': 'zh_HK',
               'zh_Hant': 'zh_TW',
               'fil': 'tl_PH'}

    language_list.extend(alias for locale, alias in six.iteritems(aliases)
                         if (locale in language_list and
                             alias not in language_list))

    _AVAILABLE_LANGUAGES[domain] = language_list
    return copy.copy(language_list)
开发者ID:epico,项目名称:oslo.i18n,代码行数:34,代码来源:_gettextutils.py


示例4: __init__

    def __init__(self, queryIndexer):
        '''
        Construct the query criteria service.
        '''
        assert isinstance(queryIndexer, QueryIndexer), 'Invalid QueryIndexer %s' % queryIndexer

        self.queryIndexer = queryIndexer
        self._locales = {code:Locale.parse(code) for code in locale_identifiers()}
开发者ID:adityaathalye,项目名称:Superdesk,代码行数:8,代码来源:query_criteria.py


示例5: test_activate_unavailable_locale

 def test_activate_unavailable_locale(self):
     unavailables = sorted(set(locale_identifiers()) -
                           set(translation.get_available_locales())) or \
                    ('en_US',)
     locale_dir = self._get_locale_dir()
     translation.add_domain('catalog1', self.env.path, locale_dir)
     translation.add_domain('catalog2', self.env.path, locale_dir)
     translation.activate(unavailables[0], self.env.path)
开发者ID:pkdevbox,项目名称:trac,代码行数:8,代码来源:translation.py


示例6: set_available_locales

def set_available_locales():
    """Set available locales for which we have translations"""
    global AVAILABLE_LOCALES
    locales=['en', 'en_US'] # these are available without translations
    for locale in localedata.locale_identifiers():
        if gettext.find('mediagoblin', TRANSLATIONS_PATH, [locale]):
            locales.append(locale)
    AVAILABLE_LOCALES = locales
开发者ID:ausbin,项目名称:mediagoblin,代码行数:8,代码来源:translate.py


示例7: __init__

 def __init__(self):
     '''
     Construct the language service.
     '''
     EntityNQServiceAlchemy.__init__(self, LanguageEntity)
     locales = [(code, Locale.parse(code)) for code in locale_identifiers()]
     locales.sort(key=lambda pack: pack[0])
     self._locales = OrderedDict(locales)
     validateProperty(LanguageEntity.Code, self._validateCode)
开发者ID:ahilles107,项目名称:Superdesk,代码行数:9,代码来源:language.py


示例8: run

    def run(self, argv=None):
        """Main entry point of the command-line interface.

        :param argv: list of arguments passed on the command-line
        """

        if argv is None:
            argv = sys.argv

        self.parser = optparse.OptionParser(usage=self.usage % ("command", "[args]"), version=self.version)
        self.parser.disable_interspersed_args()
        self.parser.print_help = self._help
        self.parser.add_option(
            "--list-locales", dest="list_locales", action="store_true", help="print all known locales and exit"
        )
        self.parser.add_option(
            "-v",
            "--verbose",
            action="store_const",
            dest="loglevel",
            const=logging.DEBUG,
            help="print as much as possible",
        )
        self.parser.add_option(
            "-q",
            "--quiet",
            action="store_const",
            dest="loglevel",
            const=logging.ERROR,
            help="print as little as possible",
        )
        self.parser.set_defaults(list_locales=False, loglevel=logging.INFO)

        options, args = self.parser.parse_args(argv[1:])

        self._configure_logging(options.loglevel)
        if options.list_locales:
            identifiers = localedata.locale_identifiers()
            longest = max([len(identifier) for identifier in identifiers])
            identifiers.sort()
            format = u"%%-%ds %%s" % (longest + 1)
            for identifier in identifiers:
                locale = Locale.parse(identifier)
                output = format % (identifier, locale.english_name)
                print(output.encode(sys.stdout.encoding or getpreferredencoding() or "ascii", "replace"))
            return 0

        if not args:
            self.parser.error("no valid command or option passed. " "Try the -h/--help option for more information.")

        cmdname = args[0]
        if cmdname not in self.commands:
            self.parser.error('unknown command "%s"' % cmdname)

        return self._dispatch(cmdname, args[1:])
开发者ID:akash0675,项目名称:babel,代码行数:55,代码来源:frontend.py


示例9: test_locale_identifiers_cache

def test_locale_identifiers_cache(monkeypatch):
    original_listdir = localedata.os.listdir
    listdir_calls = []
    def listdir_spy(*args):
        rv = original_listdir(*args)
        listdir_calls.append((args, rv))
        return rv
    monkeypatch.setattr(localedata.os, 'listdir', listdir_spy)

    # In case we've already run some tests...
    if hasattr(localedata.locale_identifiers, 'cache'):
        del localedata.locale_identifiers.cache

    assert not listdir_calls
    assert localedata.locale_identifiers()
    assert len(listdir_calls) == 1
    assert localedata.locale_identifiers() is localedata.locale_identifiers.cache
    assert len(listdir_calls) == 1
    localedata.locale_identifiers.cache = None
    assert localedata.locale_identifiers()
    assert len(listdir_calls) == 2
开发者ID:python-babel,项目名称:babel,代码行数:21,代码来源:test_localedata.py


示例10: run

    def run(self, argv=None):
        """Main entry point of the command-line interface.

        :param argv: list of arguments passed on the command-line
        """

        if argv is None:
            argv = sys.argv

        self.parser = optparse.OptionParser(usage=self.usage % ('command', '[args]'),
                                            version=self.version)
        self.parser.disable_interspersed_args()
        self.parser.print_help = self._help
        self.parser.add_option('--list-locales', dest='list_locales',
                               action='store_true',
                               help="print all known locales and exit")
        self.parser.add_option('-v', '--verbose', action='store_const',
                               dest='loglevel', const=logging.DEBUG,
                               help='print as much as possible')
        self.parser.add_option('-q', '--quiet', action='store_const',
                               dest='loglevel', const=logging.ERROR,
                               help='print as little as possible')
        self.parser.set_defaults(list_locales=False, loglevel=logging.INFO)

        options, args = self.parser.parse_args(argv[1:])

        self._configure_logging(options.loglevel)
        if options.list_locales:
            identifiers = localedata.locale_identifiers()
            longest = max([len(identifier) for identifier in identifiers])
            identifiers.sort()
            format = u'%%-%ds %%s' % (longest + 1)
            for identifier in identifiers:
                locale = Locale.parse(identifier)
                output = format % (identifier, locale.english_name)
                print(output.encode(sys.stdout.encoding or
                                    getpreferredencoding() or
                                    'ascii', 'replace'))
            return 0

        if not args:
            self.parser.error('no valid command or option passed. '
                              'Try the -h/--help option for more information.')

        cmdname = args[0]
        if cmdname not in self.commands:
            self.parser.error('unknown command "%s"' % cmdname)

        cmdinst = self._configure_command(cmdname, args[1:])
        return cmdinst.run()
开发者ID:AaronJaramillo,项目名称:shopDPM,代码行数:50,代码来源:frontend.py


示例11: get_available_languages

def get_available_languages(domain):
    """Lists the available languages for the given translation domain.

    :param domain: the domain to get languages for
    """
    if domain in _AVAILABLE_LANGUAGES:
        return copy.copy(_AVAILABLE_LANGUAGES[domain])

    localedir = os.environ.get(_locale.get_locale_dir_variable_name(domain))
    find = lambda x: gettext.find(domain,
                                  localedir=localedir,
                                  languages=[x])

    # NOTE(mrodden): en_US should always be available (and first in case
    # order matters) since our in-line message strings are en_US
    language_list = ['en_US']
    locale_identifiers = localedata.locale_identifiers()
    language_list.extend(language for language in locale_identifiers
                         if find(language))

    # In Babel 1.3, locale_identifiers() doesn't list some OpenStack supported
    # locales (e.g. 'zh_CN', and 'zh_TW') so we add the locales explicitly if
    # necessary so that they are listed as supported.
    aliases = {'zh': 'zh_CN',
               'zh_Hant_HK': 'zh_HK',
               'zh_Hant': 'zh_TW',
               'fil': 'tl_PH'}
    language_list.extend(alias for locale, alias in aliases.items()
                         if (locale in language_list and
                             alias not in language_list))

    language_list.extend(alias for locale, alias in aliases.items()
                         if (locale not in language_list and
                             find(alias)))

    # In webob.acceptparse, the best_match is just match the first element in
    # the language_list, so make the precise element in front
    result = ['en_US']
    for i in language_list[1:]:
        if '_' in i:
            result.insert(1, i)
        else:
            result.append(i)

    _AVAILABLE_LANGUAGES[domain] = result
    return copy.copy(result)
开发者ID:openstack,项目名称:oslo.i18n,代码行数:46,代码来源:_gettextutils.py


示例12: get_cldr_languages

    def get_cldr_languages(self):
        """
        Helper function to extract CLDR information. Heavily relied on babel functionality
        """
        from babel import Locale, localedata, plural

        for lang in localedata.locale_identifiers():
            locale = Locale(lang)
            if not locale.english_name:
                continue

            plurals_str = plural.to_gettext(locale.plural_form)
            nplurals, pluralequation = re_plurals.match(plurals_str).groups()
            lang_aliases = set(CLDR_FALLBACK_ALIASES.get(lang, []))
            lang_aliases.add(lang)
            for alias in lang_aliases:
                yield {
                    'code': alias,
                    'fullname': locale.english_name,
                    'nplurals': int(nplurals),
                    'pluralequation': pluralequation,
                }
开发者ID:Doist,项目名称:pootle,代码行数:22,代码来源:initdb.py


示例13: join

import sys
import os
from decimal import Decimal
from collections import defaultdict
from gettext import translation
from babel import Locale, UnknownLocaleError, localedata
from babel.numbers import parse_decimal, format_currency, format_decimal
from bottle import request
from functools import lru_cache
from os.path import join
from lib import root_directory


LOCALE_DIR = join(root_directory(), 'backend', 'locale')
DEFAULT_LANGUAGE = conf.ui.default_language
SUPPORTED_LOCALES = frozenset(localedata.locale_identifiers())
APPLICATION_NAME = "boss"


def _(message):
    return message


def acceptable_languages():
    languages = languages_set_from_headers()
    languages.intersection_update(available_languages())
    languages -= {DEFAULT_LANGUAGE}

    return list(languages) if languages else [DEFAULT_LANGUAGE]

开发者ID:deti,项目名称:boss,代码行数:29,代码来源:i18n.py


示例14: test_format_scientific_quantization

def test_format_scientific_quantization():
    # Test all locales.
    for locale_code in localedata.locale_identifiers():
        assert numbers.format_scientific(
            '0.9999999999', locale=locale_code, decimal_quantization=False).find('999999999') > -1
开发者ID:JonathanRRogers,项目名称:babel,代码行数:5,代码来源:test_numbers.py


示例15: test_format_currency_long_display_name_all

def test_format_currency_long_display_name_all():
    for locale_code in localedata.locale_identifiers():
        assert numbers.format_currency(
            1, 'USD', locale=locale_code, format_type='name').find('1') > -1
        assert numbers.format_currency(
            '1', 'USD', locale=locale_code, format_type='name').find('1') > -1
开发者ID:JonathanRRogers,项目名称:babel,代码行数:6,代码来源:test_numbers.py


示例16: test_format_decimal_quantization

def test_format_decimal_quantization():
    # Test all locales.
    for locale_code in localedata.locale_identifiers():
        assert numbers.format_decimal(
            '0.9999999999', locale=locale_code, decimal_quantization=False).endswith('9999999999') is True
开发者ID:JonathanRRogers,项目名称:babel,代码行数:5,代码来源:test_numbers.py


示例17: test_mixedcased_locale

def test_mixedcased_locale():
    for l in localedata.locale_identifiers():
        locale_id = ''.join([
            methodcaller(random.choice(['lower', 'upper']))(c) for c in l])
        assert localedata.exists(locale_id)
开发者ID:Mabusto,项目名称:babel,代码行数:5,代码来源:test_localedata.py


示例18: frozenset

  'set_locale',
  'timezoneselector',
  'VALID_LANGUAGES_CODE',
  'render_template_i18n'
]

#: gettext alias
_ = gettext

#: lazy_gettext alias
_l = lazy_gettext
#: ngettext alias
_n = ngettext

#: accepted languages codes
VALID_LANGUAGES_CODE = frozenset(lang for lang in locale_identifiers()
                                 if len(lang) == 2)

def get_default_locale():
  return current_app.extensions['babel'].default_locale


def _get_locale():
  locale = flask_babel.get_locale()
  if locale is None:
    locale = get_default_locale()
  return locale


def __gettext_territory(code):
  locale = _get_locale()
开发者ID:debon,项目名称:abilian-core,代码行数:31,代码来源:i18n.py


示例19: __init__

 def __init__(self):
     '''
     Construct the country service.
     '''
     assert isinstance(self.countries, Countries), 'Invalid countries %s' % self.countries
     self._locales = {code:Locale.parse(code) for code in locale_identifiers()}
开发者ID:adityaathalye,项目名称:Superdesk,代码行数:6,代码来源:country.py


示例20: dirname

from searx import settings
from searx import logger
from searx.utils import load_module, match_language


logger = logger.getChild('engines')

engine_dir = dirname(realpath(__file__))

engines = {}

categories = {'general': []}

languages = loads(open(engine_dir + '/../data/engines_languages.json', 'r', encoding='utf-8').read())
babel_langs = [lang_parts[0] + '-' + lang_parts[-1] if len(lang_parts) > 1 else lang_parts[0]
               for lang_parts in (lang_code.split('_') for lang_code in locale_identifiers())]

engine_shortcuts = {}
engine_default_args = {'paging': False,
                       'categories': ['general'],
                       'language_support': True,
                       'supported_languages': [],
                       'safesearch': False,
                       'timeout': settings['outgoing']['request_timeout'],
                       'shortcut': '-',
                       'disabled': False,
                       'suspend_end_time': 0,
                       'continuous_errors': 0,
                       'time_range_support': False}

开发者ID:asciimoo,项目名称:searx,代码行数:29,代码来源:__init__.py



注:本文中的babel.localedata.locale_identifiers函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python messages.Catalog类代码示例发布时间:2022-05-24
下一篇:
Python localedata.load函数代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap