本文整理汇总了Python中babel.numbers.parse_pattern函数的典型用法代码示例。如果您正苦于以下问题:Python parse_pattern函数的具体用法?Python parse_pattern怎么用?Python parse_pattern使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了parse_pattern函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_decimal_formats
def parse_decimal_formats(data, tree):
decimal_formats = data.setdefault('decimal_formats', {})
for df_elem in tree.findall('.//decimalFormats'):
if _should_skip_number_elem(data, df_elem): # TODO: Support other number systems
continue
for elem in df_elem.findall('./decimalFormatLength'):
length_type = elem.attrib.get('type')
if _should_skip_elem(elem, length_type, decimal_formats):
continue
if elem.findall('./alias'):
# TODO map the alias to its target
continue
for pattern_el in elem.findall('./decimalFormat/pattern'):
pattern_type = pattern_el.attrib.get('type')
pattern = numbers.parse_pattern(text_type(pattern_el.text))
if pattern_type:
# This is a compact decimal format, see:
# https://www.unicode.org/reports/tr35/tr35-45/tr35-numbers.html#Compact_Number_Formats
# These are mapped into a `compact_decimal_formats` dictionary
# with the format {length: {count: {multiplier: pattern}}}.
# TODO: Add support for formatting them.
compact_decimal_formats = data.setdefault('compact_decimal_formats', {})
length_map = compact_decimal_formats.setdefault(length_type, {})
length_count_map = length_map.setdefault(pattern_el.attrib['count'], {})
length_count_map[pattern_type] = pattern
else:
# Regular decimal format.
decimal_formats[length_type] = pattern
示例2: parse_currency_formats
def parse_currency_formats(data, tree):
currency_formats = data.setdefault('currency_formats', {})
for currency_format in tree.findall('.//currencyFormats'):
if _should_skip_number_elem(data, currency_format): # TODO: Support other number systems
continue
for length_elem in currency_format.findall('./currencyFormatLength'):
curr_length_type = length_elem.attrib.get('type')
for elem in length_elem.findall('currencyFormat'):
type = elem.attrib.get('type')
if curr_length_type:
# Handle `<currencyFormatLength type="short">`, etc.
# TODO(3.x): use nested dicts instead of colon-separated madness
type = '%s:%s' % (type, curr_length_type)
if _should_skip_elem(elem, type, currency_formats):
continue
for child in elem.getiterator():
if child.tag == 'alias':
currency_formats[type] = Alias(
_translate_alias(['currency_formats', elem.attrib['type']],
child.attrib['path'])
)
elif child.tag == 'pattern':
pattern = text_type(child.text)
currency_formats[type] = numbers.parse_pattern(pattern)
示例3: test_parse_pattern_negative
def test_parse_pattern_negative():
# No negative format specified
np = numbers.parse_pattern(u'¤#,##0.00')
assert np.prefix == (u'¤', u'-¤')
assert np.suffix == (u'', u'')
# Negative format is specified
np = numbers.parse_pattern(u'¤#,##0.00;(¤#,##0.00)')
assert np.prefix == (u'¤', u'(¤')
assert np.suffix == (u'', u')')
# Negative sign is a suffix
np = numbers.parse_pattern(u'¤ #,##0.00;¤ #,##0.00-')
assert np.prefix == (u'¤ ', u'¤ ')
assert np.suffix == (u'', u'-')
示例4: load_i18n
def load_i18n(project_root, tell_sentry):
# Load the locales
localeDir = os.path.join(project_root, 'i18n', 'core')
locales = LOCALES
for file in os.listdir(localeDir):
try:
parts = file.split(".")
if not (len(parts) == 2 and parts[1] == "po"):
continue
lang = parts[0]
with open(os.path.join(localeDir, file)) as f:
l = locales[lang.lower()] = Locale(lang)
c = l.catalog = read_po(f)
c.plural_func = get_function_from_rule(c.plural_expr)
try:
l.countries = make_sorted_dict(COUNTRIES, l.territories)
except KeyError:
l.countries = COUNTRIES
try:
l.languages_2 = make_sorted_dict(LANGUAGES_2, l.languages)
except KeyError:
l.languages_2 = LANGUAGES_2
except Exception as e:
tell_sentry(e, {})
# Add aliases
for k, v in list(locales.items()):
locales.setdefault(ALIASES.get(k, k), v)
locales.setdefault(ALIASES_R.get(k, k), v)
for k, v in list(locales.items()):
locales.setdefault(k.split('_', 1)[0], v)
# Patch the locales to look less formal
locales['fr'].currency_formats[None] = parse_pattern('#,##0.00\u202f\xa4')
locales['fr'].currency_symbols['USD'] = '$'
示例5: format_scientific_field
def format_scientific_field(spec, prec, number, locale):
prec = SCIENTIFIC_DECIMAL_DIGITS if prec is None else int(prec)
format_ = u'0.%sE+000' % (u'#' * prec)
pattern = parse_pattern(format_)
decimal_symbol = get_decimal_symbol(locale)
string = pattern.apply(number, locale).replace(u'.', decimal_symbol)
return string.lower() if spec.islower() else string
示例6: test_parse_pattern
def test_parse_pattern():
# Original pattern is preserved
np = numbers.parse_pattern(u'¤#,##0.00')
assert np.pattern == u'¤#,##0.00'
np = numbers.parse_pattern(u'¤#,##0.00;(¤#,##0.00)')
assert np.pattern == u'¤#,##0.00;(¤#,##0.00)'
# Given a NumberPattern object, we don't return a new instance.
# However, we don't cache NumberPattern objects, so calling
# parse_pattern with the same format string will create new
# instances
np1 = numbers.parse_pattern(u'¤ #,##0.00')
np2 = numbers.parse_pattern(u'¤ #,##0.00')
assert np1 is not np2
assert np1 is numbers.parse_pattern(np1)
示例7: test_numberpattern_repr
def test_numberpattern_repr():
"""repr() outputs the pattern string"""
# This implementation looks a bit funny, but that's cause strings are
# repr'd differently in Python 2 vs 3 and this test runs under both.
format = u'¤#,##0.00;(¤#,##0.00)'
np = numbers.parse_pattern(format)
assert repr(format) in repr(np)
示例8: parse_percent_formats
def parse_percent_formats(data, tree):
percent_formats = data.setdefault('percent_formats', {})
for elem in tree.findall('.//percentFormats/percentFormatLength'):
type = elem.attrib.get('type')
if _should_skip_elem(elem, type, percent_formats):
continue
pattern = text_type(elem.findtext('percentFormat/pattern'))
percent_formats[type] = numbers.parse_pattern(pattern)
示例9: format_number
def format_number(value, digits=None):
locale = get_current_babel_locale()
if digits is None:
return format_decimal(value, locale=locale)
(min_digits, max_digits) = (
digits if isinstance(digits, tuple) else (digits, digits))
format = locale.decimal_formats.get(None)
pattern = parse_pattern(format) # type: babel.numbers.NumberPattern
return pattern.apply(value, locale, force_frac=(min_digits, max_digits))
示例10: format_float_field
def format_float_field(__, prec, number, locale):
"""Formats a fixed-point field."""
format_ = u'0.'
if prec is None:
format_ += u'#' * NUMBER_DECIMAL_DIGITS
else:
format_ += u'0' * int(prec)
pattern = parse_pattern(format_)
return pattern.apply(number, locale)
示例11: format_field
def format_field(spec, arg, value, locale):
if spec and isinstance(value, Number):
if arg:
spec += arg
try:
pattern = parse_pattern(spec)
except ValueError:
return spec
else:
return pattern.apply(value, locale)
return str(value)
示例12: parse_decimal_formats
def parse_decimal_formats(data, tree):
decimal_formats = data.setdefault('decimal_formats', {})
for elem in tree.findall('.//decimalFormats/decimalFormatLength'):
type = elem.attrib.get('type')
if _should_skip_elem(elem, type, decimal_formats):
continue
if elem.findall('./alias'):
# TODO map the alias to its target
continue
pattern = text_type(elem.findtext('./decimalFormat/pattern'))
decimal_formats[type] = numbers.parse_pattern(pattern)
示例13: parse_scientific_formats
def parse_scientific_formats(data, tree):
scientific_formats = data.setdefault('scientific_formats', {})
for sf_elem in tree.findall('.//scientificFormats'):
if _should_skip_number_elem(data, sf_elem): # TODO: Support other number systems
continue
for elem in sf_elem.findall('./scientificFormatLength'):
type = elem.attrib.get('type')
if _should_skip_elem(elem, type, scientific_formats):
continue
pattern = text_type(elem.findtext('scientificFormat/pattern'))
scientific_formats[type] = numbers.parse_pattern(pattern)
示例14: processFormats
def processFormats(self, locale, formats):
'''
Process the formats to a complete list of formats that will be used by conversion.
'''
assert isinstance(formats, dict), 'Invalid formats %s' % formats
assert isinstance(locale, Locale), 'Invalid locale %s' % locale
for clsTyp, format in formats.items():
# In here we just check that the format is valid.
try:
if clsTyp in (Number, Percentage): bn.parse_pattern(format)
elif format not in self.formats[clsTyp]: bd.parse_pattern(format)
except Exception as e:
raise FormatError('invalid %s format \'%s\' because: %s' % (clsTyp.__name__, format, str(e)))
if Number not in formats: formats[Number] = locale.decimal_formats.get(None).pattern
if Percentage not in formats: formats[Percentage] = locale.percent_formats.get(None).pattern
for clsTyp, default in self.defaults.items():
if clsTyp not in formats: formats[clsTyp] = default
return formats
示例15: parse_currency_formats
def parse_currency_formats(data, tree):
currency_formats = data.setdefault('currency_formats', {})
for length_elem in tree.findall('.//currencyFormats/currencyFormatLength'):
curr_length_type = length_elem.attrib.get('type')
for elem in length_elem.findall('currencyFormat'):
type = elem.attrib.get('type')
if curr_length_type:
# Handle `<currencyFormatLength type="short">`, etc.
type = '%s:%s' % (type, curr_length_type)
if _should_skip_elem(elem, type, currency_formats):
continue
for child in elem.getiterator():
if child.tag == 'alias':
currency_formats[type] = Alias(
_translate_alias(['currency_formats', elem.attrib['type']],
child.attrib['path'])
)
elif child.tag == 'pattern':
pattern = text_type(child.text)
currency_formats[type] = numbers.parse_pattern(pattern)