本文整理汇总了Python中babel.numbers.parse_pattern函数的典型用法代码示例。如果您正苦于以下问题:Python parse_pattern函数的具体用法?Python parse_pattern怎么用?Python parse_pattern使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了parse_pattern函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:Changaco,项目名称:babel,代码行数:30,代码来源:import_cldr.py
示例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)
开发者ID:Changaco,项目名称:babel,代码行数:25,代码来源:import_cldr.py
示例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'-')
开发者ID:gmist,项目名称:babel,代码行数:16,代码来源:test_numbers.py
示例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'] = '$'
开发者ID:cyberjacob,项目名称:www.gittip.com,代码行数:35,代码来源:wireup.py
示例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
开发者ID:what-studio,项目名称:smartformat,代码行数:7,代码来源:dotnet.py
示例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)
开发者ID:gmist,项目名称:babel,代码行数:17,代码来源:test_numbers.py
示例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)
开发者ID:gmist,项目名称:babel,代码行数:8,代码来源:test_numbers.py
示例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)
开发者ID:jtwang,项目名称:babel,代码行数:8,代码来源:import_cldr.py
示例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))
开发者ID:suutari-ai,项目名称:shuup,代码行数:9,代码来源:i18n.py
示例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)
开发者ID:what-studio,项目名称:smartformat,代码行数:9,代码来源:dotnet.py
示例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)
开发者ID:what-studio,项目名称:smartformat,代码行数:11,代码来源:dotnet.py
示例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)
开发者ID:jtwang,项目名称:babel,代码行数:11,代码来源:import_cldr.py
示例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)
开发者ID:Changaco,项目名称:babel,代码行数:11,代码来源:import_cldr.py
示例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
开发者ID:ahilles107,项目名称:Superdesk,代码行数:22,代码来源:text_conversion.py
示例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)
开发者ID:jtwang,项目名称:babel,代码行数:20,代码来源:import_cldr.py
示例16: load_i18n
def load_i18n(website):
# Load the locales
key = lambda t: strip_accents(t[1])
localeDir = os.path.join(website.project_root, 'i18n', 'core')
locales = website.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_map = {k: l.territories[k] for k in COUNTRIES_MAP}
l.countries = sorted(l.countries_map.items(), key=key)
except KeyError:
l.countries_map = COUNTRIES_MAP
l.countries = COUNTRIES
except Exception as e:
website.tell_sentry(e)
# Add the default English locale
locale_en = website.locale_en = locales['en'] = Locale('en')
locale_en.catalog = Catalog('en')
locale_en.catalog.plural_func = lambda n: n != 1
locale_en.countries = COUNTRIES
locale_en.countries_map = COUNTRIES_MAP
# 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'] = '$'
开发者ID:webmaven,项目名称:gratipay.com,代码行数:41,代码来源:wireup.py
示例17: test_parse_static_pattern
def test_parse_static_pattern():
assert numbers.parse_pattern('Kun') # in the So locale in CLDR 30
开发者ID:JonathanRRogers,项目名称:babel,代码行数:2,代码来源:test_numbers.py
示例18: main
#.........这里部分代码省略.........
widths[int(elem.attrib["type"])] = text_type(elem.text)
elif elem.tag == "alias":
ctxts[width_type] = Alias(
_translate_alias(["quarters", ctxt_type, width_type], elem.attrib["path"])
)
eras = data.setdefault("eras", {})
for width in calendar.findall("eras/*"):
width_type = NAME_MAP[width.tag]
widths = eras.setdefault(width_type, {})
for elem in width.getiterator():
if elem.tag == "era":
if ("draft" in elem.attrib or "alt" in elem.attrib) and int(elem.attrib["type"]) in widths:
continue
widths[int(elem.attrib.get("type"))] = text_type(elem.text)
elif elem.tag == "alias":
eras[width_type] = Alias(_translate_alias(["eras", width_type], elem.attrib["path"]))
# AM/PM
periods = data.setdefault("periods", {})
for day_period_width in calendar.findall("dayPeriods/dayPeriodContext/dayPeriodWidth"):
if day_period_width.attrib["type"] == "wide":
for day_period in day_period_width.findall("dayPeriod"):
if "alt" not in day_period.attrib:
periods[day_period.attrib["type"]] = text_type(day_period.text)
date_formats = data.setdefault("date_formats", {})
for format in calendar.findall("dateFormats"):
for elem in format.getiterator():
if elem.tag == "dateFormatLength":
if "draft" in elem.attrib and elem.attrib.get("type") in date_formats:
continue
try:
date_formats[elem.attrib.get("type")] = dates.parse_pattern(
text_type(elem.findtext("dateFormat/pattern"))
)
except ValueError as e:
error(e)
elif elem.tag == "alias":
date_formats = Alias(_translate_alias(["date_formats"], elem.attrib["path"]))
time_formats = data.setdefault("time_formats", {})
for format in calendar.findall("timeFormats"):
for elem in format.getiterator():
if elem.tag == "timeFormatLength":
if ("draft" in elem.attrib or "alt" in elem.attrib) and elem.attrib.get("type") in time_formats:
continue
try:
time_formats[elem.attrib.get("type")] = dates.parse_pattern(
text_type(elem.findtext("timeFormat/pattern"))
)
except ValueError as e:
error(e)
elif elem.tag == "alias":
time_formats = Alias(_translate_alias(["time_formats"], elem.attrib["path"]))
datetime_formats = data.setdefault("datetime_formats", {})
for format in calendar.findall("dateTimeFormats"):
for elem in format.getiterator():
if elem.tag == "dateTimeFormatLength":
if ("draft" in elem.attrib or "alt" in elem.attrib) and elem.attrib.get(
"type"
) in datetime_formats:
continue
try:
datetime_formats[elem.attrib.get("type")] = text_type(
开发者ID:josephbreihan,项目名称:babel,代码行数:67,代码来源:import_cldr.py
示例19: load_langs
l.countries = COUNTRIES
return langs
# Load the locales
LOCALES = load_langs("i18n")
# Add the default English locale
LOCALE_EN = LOCALES['en'] = Locale('en')
LOCALE_EN.catalog = Catalog('en')
LOCALE_EN.catalog.plural_func = lambda n: n != 1
LOCALE_EN.countries = COUNTRIES
LOCALE_EN.countries_map = COUNTRIES_MAP
# Patch the locales to look less formal
LOCALE_EN.currency_formats[None] = parse_pattern('\xa4#,##0.##')
LOCALES['fr'].currency_formats[None] = parse_pattern('#,##0.##\u202f\xa4')
LOCALES['fr'].currency_symbols['USD'] = '$'
def get_locale_for_request(request):
accept_lang = request.headers.get("Accept-Language", "")
languages = (lang.split(";", 1)[0] for lang in accept_lang.split(","))
for lang in languages:
lang = regularize_locale(lang)
loc = LOCALES.get(lang)
if loc:
return loc
return LOCALE_EN
开发者ID:maryannbanks,项目名称:www.gittip.com,代码行数:29,代码来源:i18n.py
示例20: main
#.........这里部分代码省略.........
width_type = NAME_MAP[width.tag]
widths = eras.setdefault(width_type, {})
for elem in width.getiterator():
if elem.tag == 'era':
if ('draft' in elem.attrib or 'alt' in elem.attrib) \
and int(elem.attrib['type']) in widths:
continue
widths[int(elem.attrib.get('type'))] = text_type(elem.text)
elif elem.tag == 'alias':
eras[width_type] = Alias(
_translate_alias(['eras', width_type],
elem.attrib['path'])
)
# AM/PM
periods = data.setdefault('periods', {})
for day_period_width in calendar.findall(
'dayPeriods/dayPeriodContext/dayPeriodWidth'):
if day_period_width.attrib['type'] == 'wide':
for day_period in day_period_width.findall('dayPeriod'):
if 'alt' not in day_period.attrib:
periods[day_period.attrib['type']] = text_type(
day_period.text)
date_formats = data.setdefault('date_formats', {})
for format in calendar.findall('dateFormats'):
for elem in format.getiterator():
if elem.tag == 'dateFormatLength':
if 'draft' in elem.attrib and \
elem.attrib.get('type') in date_formats:
continue
try:
date_formats[elem.attrib.get('type')] = \
dates.parse_pattern(text_type(
elem.findtext('dateFormat/pattern')))
except ValueError as e:
error(e)
elif elem.tag == 'alias':
date_formats = Alias(_translate_alias(
['date_formats'], elem.attrib['path'])
)
time_formats = data.setdefault('time_formats', {})
for format in calendar.findall('timeFormats'):
for elem in format.getiterator():
if elem.tag == 'timeFormatLength':
if ('draft' in elem.attrib or 'alt' in elem.attrib) \
and elem.attrib.get('type') in time_formats:
continue
try:
time_formats[elem.attrib.get('type')] = \
dates.parse_pattern(text_type(
elem.findtext('timeFormat/pattern')))
except ValueError as e:
error(e)
elif elem.tag == 'alias':
time_formats = Alias(_translate_alias(
['time_formats'], elem.attrib['path'])
)
datetime_formats = data.setdefault('datetime_formats', {})
for format in calendar.findall('dateTimeFormats'):
for elem in format.getiterator():
if elem.tag == 'dateTimeFormatLength':
if ('draft' in elem.attrib or 'alt' in elem.attrib) \
and elem.attrib.get('type') in datetime_formats:
开发者ID:rjollos,项目名称:babel,代码行数:67,代码来源:import_cldr.py
注:本文中的babel.numbers.parse_pattern函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论