本文整理汇总了Python中babel.core.Locale.parse方法的典型用法代码示例。如果您正苦于以下问题:Python Locale.parse方法的具体用法?Python Locale.parse怎么用?Python Locale.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类babel.core.Locale
的用法示例。
在下文中一共展示了Locale.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getLocale
# 需要导入模块: from babel.core import Locale [as 别名]
# 或者: from babel.core.Locale import parse [as 别名]
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()
示例2: get_locale_data
# 需要导入模块: from babel.core import Locale [as 别名]
# 或者: from babel.core.Locale import parse [as 别名]
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
示例3: getGlobalPOTimestamp
# 需要导入模块: from babel.core import Locale [as 别名]
# 或者: from babel.core.Locale import parse [as 别名]
def getGlobalPOTimestamp(self, locale):
'''
@see: IPOFileManager.getGlobalPOTimestamp
'''
try: locale = Locale.parse(locale)
except UnknownLocaleError: raise InvalidLocaleError(locale)
return self._lastModified(locale)
示例4: get_locale
# 需要导入模块: from babel.core import Locale [as 别名]
# 或者: from babel.core.Locale import parse [as 别名]
def get_locale(lang):
"""Return a babel Locale object for lang. defaults to LANGUAGE_CODE."""
lang = babel_format_locale_map.get(lang) or lang
try:
return Locale.parse(lang, sep='-')
except (UnknownLocaleError, ValueError):
return Locale(*settings.LANGUAGE_CODE.split('-'))
示例5: _set_mime_headers
# 需要导入模块: from babel.core import Locale [as 别名]
# 或者: from babel.core.Locale import parse [as 别名]
def _set_mime_headers(self, headers):
for name, value in headers:
name = name.lower()
if name == 'project-id-version':
parts = value.split(' ')
self.project = u' '.join(parts[:-1])
self.version = parts[-1]
elif name == 'report-msgid-bugs-to':
self.msgid_bugs_address = value
elif name == 'last-translator':
self.last_translator = value
elif name == 'language':
self.locale = Locale.parse(value)
elif name == 'language-team':
self.language_team = value
elif name == 'content-type':
mimetype, params = parse_header(value)
if 'charset' in params:
self.charset = params['charset'].lower()
elif name == 'plural-forms':
_, params = parse_header(' ;' + value)
self._num_plurals = int(params.get('nplurals', 2))
self._plural_expr = params.get('plural', '(n != 1)')
elif name == 'pot-creation-date':
self.creation_date = _parse_datetime_header(value)
elif name == 'po-revision-date':
# Keep the value if it's not the default one
if 'YEAR' not in value:
self.revision_date = _parse_datetime_header(value)
示例6: parse_decimal
# 需要导入模块: from babel.core import Locale [as 别名]
# 或者: from babel.core.Locale import parse [as 别名]
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)
示例7: format_scientific
# 需要导入模块: from babel.core import Locale [as 别名]
# 或者: from babel.core.Locale import parse [as 别名]
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)
示例8: _format_currency_long_name
# 需要导入模块: from babel.core import Locale [as 别名]
# 或者: from babel.core.Locale import parse [as 别名]
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)
示例9: get_currency_unit_pattern
# 需要导入模块: from babel.core import Locale [as 别名]
# 或者: from babel.core.Locale import parse [as 别名]
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']
示例10: babel_date
# 需要导入模块: from babel.core import Locale [as 别名]
# 或者: from babel.core.Locale import parse [as 别名]
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)
示例11: format_list
# 需要导入模块: from babel.core import Locale [as 别名]
# 或者: from babel.core.Locale import parse [as 别名]
def format_list(lst, locale=DEFAULT_LOCALE):
""" Formats `lst` as a list
e.g.
>>> format_list(['apples', 'oranges', 'pears'], 'en')
u'apples, oranges, and pears'
>>> format_list(['apples', 'oranges', 'pears'], 'zh')
u'apples\u3001oranges\u548cpears'
:param lst: a sequence of items to format in to a list
:param locale: the locale
"""
locale = Locale.parse(locale)
if not lst:
return ''
if len(lst) == 1:
return lst[0]
if len(lst) == 2:
return locale.list_patterns['2'].format(*lst)
result = locale.list_patterns['start'].format(lst[0], lst[1])
for elem in lst[2:-1]:
result = locale.list_patterns['middle'].format(result, elem)
result = locale.list_patterns['end'].format(result, lst[-1])
return result
示例12: format_skeleton
# 需要导入模块: from babel.core import Locale [as 别名]
# 或者: from babel.core.Locale import parse [as 别名]
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)
示例13: _language_select
# 需要导入模块: from babel.core import Locale [as 别名]
# 或者: from babel.core.Locale import parse [as 别名]
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
示例14: parse_decimal
# 需要导入模块: from babel.core import Locale [as 别名]
# 或者: from babel.core.Locale import parse [as 别名]
def parse_decimal(string, locale=LC_NUMERIC):
"""Parse localized decimal string into a decimal.
>>> parse_decimal('1,099.98', locale='en_US')
Decimal('1099.98')
>>> parse_decimal('1.099,98', locale='de')
Decimal('1099.98')
When the given string cannot be parsed, an exception is raised:
>>> try:
... parse_decimal('2,109,998', locale='de')
... except NumberFormatError as e:
... msg = str(e)
>>> msg
"'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: `Decimal`
:raise `NumberFormatError`: if the string can not be converted to a
decimal number
"""
locale = Locale.parse(locale)
try:
return Decimal(string.replace(get_group_symbol(locale), '')
.replace(get_decimal_symbol(locale), '.'))
except InvalidOperation:
raise NumberFormatError("'%s' is not a valid decimal number" % string)
示例15: parse_decimal
# 需要导入模块: from babel.core import Locale [as 别名]
# 或者: from babel.core.Locale import parse [as 别名]
def parse_decimal(string, locale=LC_NUMERIC):
"""Parse localized decimal string into a decimal.
>>> parse_decimal('1,099.98', locale='en_US')
Decimal('1099.98')
>>> parse_decimal('1.099,98', locale='de')
Decimal('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
:raise NumberFormatError: if the string can not be converted to a
decimal number
"""
locale = Locale.parse(locale)
try:
return Decimal(string.replace(get_group_symbol(locale), '')
.replace(get_decimal_symbol(locale), '.'))
except InvalidOperation:
raise NumberFormatError('%r is not a valid decimal number' % string)