本文整理汇总了Python中babel.core.Locale类的典型用法代码示例。如果您正苦于以下问题:Python Locale类的具体用法?Python Locale怎么用?Python Locale使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Locale类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_negotiate
def test_negotiate(self):
de_DE = Locale.negotiate(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
assert (de_DE.language, de_DE.territory) == ('de', 'DE')
de = Locale.negotiate(['de_DE', 'en_US'], ['en', 'de'])
assert (de.language, de.territory) == ('de', None)
nothing = Locale.negotiate(['de_DE', 'de'], ['en_US'])
assert nothing is None
开发者ID:adamchainz,项目名称:babel,代码行数:7,代码来源:test_core.py
示例2: get_metadata
def get_metadata(app, docname):
'''
Extracts metadata from a document.
'''
env = app.builder.env
language = app.config.language
locale = Locale.parse(language) if language else Locale.default()
format_ui_date = partial(
format_date, format=UIStr.TIMESTAMP_FMT, locale=locale)
format_short_ui_short = partial(
format_date, format=UIStr.TIMESTAMP_FMT_SHORT, locale=locale)
env.blog_metadata[docname] = Metadata()
metadata = env.blog_metadata[docname]
# if it's a page
if docname.startswith("pages/"):
metadata.is_page = True
return
# posts are identified by ($YEAR)/($MONTH)/($DAY) paths
match = re.match(r"\d{4}/\d{2}/\d{2}/", docname)
# if not post return
if not match:
return
metadata.is_post = True
metadata.link = docname
metadata.date = datetime.datetime.strptime(match.group(), "%Y/%m/%d/")
# we format date here instead of inside template due to localization issues
# and Python2 vs Python3 incompatibility
metadata.formatted_date = format_ui_date(metadata.date)
metadata.formatted_date_short = format_short_ui_short(metadata.date)
开发者ID:jean,项目名称:tinkerer,代码行数:35,代码来源:metadata.py
示例3: test_value_error
def test_value_error(self, Locale):
"""
If Locale.parse raises a ValueError, return the en-US locale
object.
"""
Locale.parse.side_effect = ValueError
eq_(helpers.current_locale(), Locale.return_value)
Locale.assert_called_with('en', 'US')
开发者ID:NIRVIT,项目名称:bedrock,代码行数:8,代码来源:test_helpers.py
示例4: test_unknown_locale
def test_unknown_locale(self, Locale):
"""
If Locale.parse raises an UnknownLocaleError, return the en-US
locale object.
"""
Locale.parse.side_effect = UnknownLocaleError('foo')
eq_(helpers.current_locale(), Locale.return_value)
Locale.assert_called_with('en', 'US')
开发者ID:NIRVIT,项目名称:bedrock,代码行数:8,代码来源:test_helpers.py
示例5: getLocale
def getLocale(self, request):
## FIXME: implement request.locale()
tags = ACCEPT_LANGUAGE.parse(request.environ())
if tags:
try:
return Locale.parse(tags[0], sep='-')
except UnknownLocaleError, e:
try:
return Locale.parse(tags[0])
except UnknownLocaleError, e:
logger.error('Locale parsing error: %s' % e)
return defaultLocale()
开发者ID:MatiasNAmendola,项目名称:muntjac,代码行数:12,代码来源:paste_wsgi_servlet.py
示例6: negotiate
def negotiate(cls, locale):
"""
Negotiate proper RBNF rules based on global data
item `rbnf_locales`
Caching is not necessary the Locale object does that pretty well
"""
loc = Locale.negotiate([str(Locale.parse(locale))], get_global('rbnf_locales'))
print('TL', type(loc))
return cls(loc)
开发者ID:blagasz,项目名称:babel,代码行数:12,代码来源:rbnf.py
示例7: defaultLocale
def defaultLocale():
try:
lang, _ = locale.getdefaultlocale()
except Exception:
lang = None
if lang is not None:
return Locale.parse(lang)
else:
try:
return Locale.default()
except UnknownLocaleError:
return Locale('en', 'US')
开发者ID:AvdN,项目名称:muntjac,代码行数:13,代码来源:util.py
示例8: get_locale_data
def get_locale_data():
language = get_language()
if not language:
language = settings.LANGUAGE_CODE
locale_code = to_locale(language)
locale = None
try:
locale = Locale.parse(locale_code)
except (ValueError, UnknownLocaleError):
# Invalid format or unknown locale
# Fallback to the default language
language = settings.LANGUAGE_CODE
locale_code = to_locale(language)
locale = Locale.parse(locale_code)
return locale, locale_code
开发者ID:mirumee,项目名称:django-prices,代码行数:15,代码来源:prices_i18n.py
示例9: format_percent
def format_percent(number, format=None, locale=LC_NUMERIC):
"""Return formatted percent value for a specific locale.
>>> format_percent(0.34, locale='en_US') == u('34%')
True
>>> format_percent(25.1234, locale='en_US') == u('2,512%')
True
>>> format_percent(25.1234, locale='sv_SE') == u('2\\xa0512\\xa0%')
True
The format pattern can also be specified explicitly:
>>> format_percent(25.1234, u('#,##0\u2030'), locale='en_US') == u('25,123\u2030')
True
:param number: the percent number to format
:param format:
:param locale: the `Locale` object or locale identifier
:return: the formatted percent number
:rtype: `unicode`
"""
locale = Locale.parse(locale)
if not format:
format = locale.percent_formats.get(format)
pattern = parse_pattern(format)
return pattern.apply(number, locale)
开发者ID:AtomLaw,项目名称:Ally-Py,代码行数:26,代码来源:numbers.py
示例10: format_currency
def format_currency(number, currency, format=None, locale=LC_NUMERIC):
"""Return formatted currency value.
>>> format_currency(1099.98, 'USD', locale='en_US') == u('$1,099.98')
True
>>> format_currency(1099.98, 'USD', locale='es_CO') == u('US$\\xa01.099,98')
True
>>> format_currency(1099.98, 'EUR', locale='de_DE') == u('1.099,98\\xa0\\u20ac')
True
The pattern can also be specified explicitly:
>>> format_currency(1099.98, 'EUR', u('\u00a4\u00a4 #,##0.00'), locale='en_US') == u('EUR 1,099.98')
True
:param number: the number to format
:param currency: the currency code
:param locale: the `Locale` object or locale identifier
:return: the formatted currency value
:rtype: `unicode`
"""
locale = Locale.parse(locale)
if not format:
format = locale.currency_formats.get(format)
pattern = parse_pattern(format)
return pattern.apply(number, locale, currency=currency)
开发者ID:AtomLaw,项目名称:Ally-Py,代码行数:26,代码来源:numbers.py
示例11: _language_select
def _language_select(self):
out = {'automatic': _('automatic')}
i18n_dir = os.path.join(xdm.APP_PATH, 'i18n')
# http://stackoverflow.com/questions/800197/get-all-of-the-immediate-subdirectories-in-python
for language in [name for name in os.listdir(i18n_dir) if os.path.isdir(os.path.join(i18n_dir, name))]:
out[language] = Locale.parse(language, sep='_').display_name
return out
开发者ID:parksnico,项目名称:XDM,代码行数:7,代码来源:System.py
示例12: getGlobalPOTimestamp
def getGlobalPOTimestamp(self, locale):
'''
@see: IPOFileManager.getGlobalPOTimestamp
'''
try: locale = Locale.parse(locale)
except UnknownLocaleError: raise InvalidLocaleError(locale)
return self._lastModified(locale)
开发者ID:AtomLaw,项目名称:Ally-Py,代码行数:7,代码来源:po_file_manager.py
示例13: format_skeleton
def format_skeleton(skeleton, datetime=None, tzinfo=None, locale=LC_TIME):
r"""Return a time and/or date formatted according to the given pattern.
The skeletons are defined in the CLDR data and provide more flexibility
than the simple short/long/medium formats, but are a bit harder to use.
The are defined using the date/time symbols without order or punctuation
and map to a suitable format for the given locale.
>>> t = datetime(2007, 4, 1, 15, 30)
>>> format_skeleton('MMMEd', t, locale='fr')
u'dim. 1 avr.'
>>> format_skeleton('MMMEd', t, locale='en')
u'Sun, Apr 1'
After the skeleton is resolved to a pattern `format_datetime` is called so
all timezone processing etc is the same as for that.
:param skeleton: A date time skeleton as defined in the cldr data.
:param datetime: the ``time`` or ``datetime`` object; if `None`, the current
time in UTC is used
:param tzinfo: the time-zone to apply to the time for display
:param locale: a `Locale` object or a locale identifier
"""
locale = Locale.parse(locale)
format = locale.datetime_skeletons[skeleton]
return format_datetime(datetime, format, tzinfo, locale)
开发者ID:ENuge,项目名称:babel,代码行数:26,代码来源:dates.py
示例14: babel_date
def babel_date(date, format='long'):
"""
Format a date properly for the current locale. Format can be one of
'short', 'medium', 'long', or 'full'.
"""
locale = Locale.parse(get_language(), sep='-')
return format_date(date, format, locale)
开发者ID:stephendonner,项目名称:affiliates,代码行数:7,代码来源:helpers.py
示例15: _babel_locale
def _babel_locale():
"""Return the current locale in Babel's format."""
try:
return Locale.parse(get_language(), sep='-')
except UnknownLocaleError:
# Default to en-US
return Locale('en', 'US')
开发者ID:bensternthal,项目名称:firefox-flicks,代码行数:7,代码来源:helpers.py
示例16: parse_decimal
def parse_decimal(string, locale=LC_NUMERIC):
"""Parse localized decimal string into a float.
>>> parse_decimal('1,099.98', locale='en_US')
1099.98
>>> parse_decimal('1.099,98', locale='de')
1099.98
When the given string cannot be parsed, an exception is raised:
>>> parse_decimal('2,109,998', locale='de')
Traceback (most recent call last):
...
NumberFormatError: '2,109,998' is not a valid decimal number
:param string: the string to parse
:param locale: the `Locale` object or locale identifier
:return: the parsed decimal number
:rtype: `float`
:raise `NumberFormatError`: if the string can not be converted to a
decimal number
"""
locale = Locale.parse(locale)
try:
return float(string.replace(get_group_symbol(locale), "").replace(get_decimal_symbol(locale), "."))
except ValueError:
raise NumberFormatError("%r is not a valid decimal number" % string)
开发者ID:2013Commons,项目名称:HUE-SHARK,代码行数:27,代码来源:numbers.py
示例17: format_scientific
def format_scientific(
number, format=None, locale=LC_NUMERIC, decimal_quantization=True):
"""Return value formatted in scientific notation for a specific locale.
>>> format_scientific(10000, locale='en_US')
u'1E4'
The format pattern can also be specified explicitly:
>>> format_scientific(1234567, u'##0.##E00', locale='en_US')
u'1.23E06'
By default the locale is allowed to truncate and round a high-precision
number by forcing its format pattern onto the decimal part. You can bypass
this behavior with the `decimal_quantization` parameter:
>>> format_scientific(1234.9876, u'#.##E0', locale='en_US')
u'1.23E3'
>>> format_scientific(1234.9876, u'#.##E0', locale='en_US', decimal_quantization=False)
u'1.2349876E3'
:param number: the number to format
:param format:
:param locale: the `Locale` object or locale identifier
:param decimal_quantization: Truncate and round high-precision numbers to
the format pattern. Defaults to `True`.
"""
locale = Locale.parse(locale)
if not format:
format = locale.scientific_formats.get(format)
pattern = parse_pattern(format)
return pattern.apply(
number, locale, decimal_quantization=decimal_quantization)
开发者ID:python-babel,项目名称:babel,代码行数:33,代码来源:numbers.py
示例18: _format_currency_long_name
def _format_currency_long_name(
number, currency, format=None, locale=LC_NUMERIC, currency_digits=True,
format_type='standard', decimal_quantization=True):
# Algorithm described here:
# https://www.unicode.org/reports/tr35/tr35-numbers.html#Currencies
locale = Locale.parse(locale)
# Step 1.
# There are no examples of items with explicit count (0 or 1) in current
# locale data. So there is no point implementing that.
# Step 2.
# Correct number to numeric type, important for looking up plural rules:
if isinstance(number, string_types):
number_n = float(number)
else:
number_n = number
# Step 3.
unit_pattern = get_currency_unit_pattern(currency, count=number_n, locale=locale)
# Step 4.
display_name = get_currency_name(currency, count=number_n, locale=locale)
# Step 5.
if not format:
format = locale.decimal_formats.get(format)
pattern = parse_pattern(format)
number_part = pattern.apply(
number, locale, currency=currency, currency_digits=currency_digits,
decimal_quantization=decimal_quantization)
return unit_pattern.format(number_part, display_name)
开发者ID:python-babel,项目名称:babel,代码行数:34,代码来源:numbers.py
示例19: get_currency_unit_pattern
def get_currency_unit_pattern(currency, count=None, locale=LC_NUMERIC):
"""
Return the unit pattern used for long display of a currency value
for a given locale.
This is a string containing ``{0}`` where the numeric part
should be substituted and ``{1}`` where the currency long display
name should be substituted.
>>> get_currency_unit_pattern('USD', locale='en_US', count=10)
u'{0} {1}'
.. versionadded:: 2.7.0
:param currency: the currency code.
:param count: the optional count. If provided the unit
pattern for that number will be returned.
:param locale: the `Locale` object or locale identifier.
"""
loc = Locale.parse(locale)
if count is not None:
plural_form = loc.plural_form(count)
try:
return loc._data['currency_unit_patterns'][plural_form]
except LookupError:
# Fall back to 'other'
pass
return loc._data['currency_unit_patterns']['other']
开发者ID:python-babel,项目名称:babel,代码行数:28,代码来源:numbers.py
示例20: get_plural
def get_plural(locale=LC_CTYPE):
"""A tuple with the information catalogs need to perform proper
pluralization. The first item of the tuple is the number of plural
forms, the second the plural expression.
>>> get_plural(locale='en')
(2, '(n != 1)')
>>> get_plural(locale='ga')
(3, '(n==1 ? 0 : n==2 ? 1 : 2)')
The object returned is a special tuple with additional members:
>>> tup = get_plural("ja")
>>> tup.num_plurals
1
>>> tup.plural_expr
'0'
>>> tup.plural_forms
'npurals=1; plural=0'
Converting the tuple into a string prints the plural forms for a
gettext catalog:
>>> str(tup)
'npurals=1; plural=0'
"""
locale = Locale.parse(locale)
try:
tup = PLURALS[str(locale)]
except KeyError:
try:
tup = PLURALS[locale.language]
except KeyError:
tup = DEFAULT_PLURAL
return _PluralTuple(tup)
开发者ID:AgentJay,项目名称:webapp-improved,代码行数:35,代码来源:plurals.py
注:本文中的babel.core.Locale类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论