本文整理汇总了Python中babel.core.get_global函数的典型用法代码示例。如果您正苦于以下问题:Python get_global函数的具体用法?Python get_global怎么用?Python get_global使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_global函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: match_language
def match_language(locale_code, lang_list=[], custom_aliases={}, fallback='en-US'):
# try to get language from given locale_code
language = _match_language(locale_code, lang_list, custom_aliases)
if language:
return language
locale_parts = locale_code.split('-')
lang_code = locale_parts[0]
# try to get language using an equivalent country code
if len(locale_parts) > 1:
country_alias = get_global('territory_aliases').get(locale_parts[-1])
if country_alias:
language = _match_language(lang_code + '-' + country_alias[0], lang_list, custom_aliases)
if language:
return language
# try to get language using an equivalent language code
alias = get_global('language_aliases').get(lang_code)
if alias:
language = _match_language(alias, lang_list, custom_aliases)
if language:
return language
if lang_code != locale_code:
# try to get language from given language without giving the country
language = _match_language(lang_code, lang_list, custom_aliases)
return language or fallback
示例2: _babel_has_locale_data
def _babel_has_locale_data():
from babel import core
try:
core.get_global(None)
return True
except RuntimeError:
return False
示例3: get_currency_fraction
def get_currency_fraction(currency):
fractions = get_global('currency_fractions')
try:
fraction = fractions[currency]
except KeyError:
fraction = fractions['DEFAULT']
return fraction[0]
示例4: get_territory_language_info
def get_territory_language_info(territory):
"""
Get a dictionary of language information for a territory.
The dictionary is keyed by language code; the values are dicts with more information.
The following keys are currently known for the values:
* `population_percent`: The percentage of the territory's population speaking the
language.
* `official_status`: An optional string describing the officiality status of the language.
Known values are "official", "official_regional" and "de_facto_official".
.. warning:: Note that the data is as up to date as the current version of the CLDR used
by Babel. If you need scientifically accurate information, use another source!
.. note:: Note that the format of the dict returned may change between Babel versions.
See http://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html
:param territory: Territory code
:type territory: str
:return: Language information dictionary
:rtype: dict[str, dict]
"""
territory = str(territory).upper()
return get_global("territory_languages").get(territory, {}).copy()
示例5: test_basic
def test_basic(self):
print('RL', get_global('rbnf_locales'))
x = rbnf.RuleBasedNumberFormat.negotiate('hu_HU')
print('L', x._locale)
print('RR', x.available_rulesets)
assert x.format(20) == "húsz"
示例6: load
def load(name, merge_inherited=True):
"""Load the locale data for the given locale.
The locale data is a dictionary that contains much of the data defined by
the Common Locale Data Repository (CLDR). This data is stored as a
collection of pickle files inside the ``babel`` package.
>>> d = load('en_US')
>>> d['languages']['sv']
u'Swedish'
Note that the results are cached, and subsequent requests for the same
locale return the same dictionary:
>>> d1 = load('en_US')
>>> d2 = load('en_US')
>>> d1 is d2
True
:param name: the locale identifier string (or "root")
:param merge_inherited: whether the inherited data should be merged into
the data of the requested locale
:raise `IOError`: if no locale data file is found for the given locale
identifer, or one of the locales it inherits from
"""
_cache_lock.acquire()
try:
data = _cache.get(name)
if not data:
# Load inherited data
if name == 'root' or not merge_inherited:
data = {}
else:
from babel.core import get_global
parent = get_global('parent_exceptions').get(name)
if not parent:
parts = name.split('_')
if len(parts) == 1:
parent = 'root'
else:
parent = '_'.join(parts[:-1])
data = load(parent).copy()
filename = os.path.join(_dirname, '%s.dat' % name)
fileobj = open(filename, 'rb')
try:
if name != 'root' and merge_inherited:
merge(data, pickle.load(fileobj))
else:
data = pickle.load(fileobj)
_cache[name] = data
finally:
fileobj.close()
return data
finally:
_cache_lock.release()
示例7: 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)
示例8: get_currency_precision
def get_currency_precision(currency):
"""Return currency's precision.
Precision is the number of decimals found after the decimal point in the
currency's format pattern.
.. versionadded:: 2.5.0
:param currency: the currency code.
"""
precisions = get_global('currency_fractions')
return precisions.get(currency, precisions['DEFAULT'])[0]
示例9: list_currencies
def list_currencies(locale=None):
""" Return a `set` of normalized currency codes.
.. versionadded:: 2.5.0
:param locale: filters returned currency codes by the provided locale.
Expected to be a locale instance or code. If no locale is
provided, returns the list of all currencies from all
locales.
"""
# Get locale-scoped currencies.
if locale:
currencies = Locale.parse(locale).currencies.keys()
else:
currencies = get_global('all_currencies')
return set(currencies)
示例10: get_official_languages
def get_official_languages(territory, regional=False, de_facto=False):
"""
Get the official language(s) for the given territory.
The language codes, if any are known, are returned in order of descending popularity.
If the `regional` flag is set, then languages which are regionally official are also returned.
If the `de_facto` flag is set, then languages which are "de facto" official are also returned.
.. warning:: Note that the data is as up to date as the current version of the CLDR used
by Babel. If you need scientifically accurate information, use another source!
:param territory: Territory code
:type territory: str
:param regional: Whether to return regionally official languages too
:type regional: bool
:param de_facto: Whether to return de-facto official languages too
:type de_facto: bool
:return: Tuple of language codes
:rtype: tuple[str]
"""
territory = str(territory).upper()
allowed_stati = set(("official",))
if regional:
allowed_stati.add("official_regional")
if de_facto:
allowed_stati.add("de_facto_official")
languages = get_global("territory_languages").get(territory, {})
pairs = [
(info['population_percent'], language)
for language, info in languages.items()
if info.get('official_status') in allowed_stati
]
pairs.sort(reverse=True)
return tuple(lang for _, lang in pairs)
示例11: _match_language
def _match_language(lang_code, lang_list=[], custom_aliases={}):
# replace language code with a custom alias if necessary
if lang_code in custom_aliases:
lang_code = custom_aliases[lang_code]
if lang_code in lang_list:
return lang_code
# try to get the most likely country for this language
subtags = get_global('likely_subtags').get(lang_code)
if subtags:
subtag_parts = subtags.split('_')
new_code = subtag_parts[0] + '-' + subtag_parts[-1]
if new_code in custom_aliases:
new_code = custom_aliases[new_code]
if new_code in lang_list:
return new_code
# try to get the any supported country for this language
for lc in lang_list:
if lang_code == lc.split('-')[0]:
return lc
return None
示例12: get_territory_currencies
def get_territory_currencies(territory, start_date=None, end_date=None,
tender=True, non_tender=False,
include_details=False):
"""Returns the list of currencies for the given territory that are valid for
the given date range. In addition to that the currency database
distinguishes between tender and non-tender currencies. By default only
tender currencies are returned.
The return value is a list of all currencies roughly ordered by the time
of when the currency became active. The longer the currency is being in
use the more to the left of the list it will be.
The start date defaults to today. If no end date is given it will be the
same as the start date. Otherwise a range can be defined. For instance
this can be used to find the currencies in use in Austria between 1995 and
2011:
>>> from datetime import date
>>> get_territory_currencies('AT', date(1995, 1, 1), date(2011, 1, 1))
['ATS', 'EUR']
Likewise it's also possible to find all the currencies in use on a
single date:
>>> get_territory_currencies('AT', date(1995, 1, 1))
['ATS']
>>> get_territory_currencies('AT', date(2011, 1, 1))
['EUR']
By default the return value only includes tender currencies. This
however can be changed:
>>> get_territory_currencies('US')
['USD']
>>> get_territory_currencies('US', tender=False, non_tender=True,
... start_date=date(2014, 1, 1))
['USN', 'USS']
.. versionadded:: 2.0
:param territory: the name of the territory to find the currency fo
:param start_date: the start date. If not given today is assumed.
:param end_date: the end date. If not given the start date is assumed.
:param tender: controls whether tender currencies should be included.
:param non_tender: controls whether non-tender currencies should be
included.
:param include_details: if set to `True`, instead of returning currency
codes the return value will be dictionaries
with detail information. In that case each
dictionary will have the keys ``'currency'``,
``'from'``, ``'to'``, and ``'tender'``.
"""
currencies = get_global('territory_currencies')
if start_date is None:
start_date = date_.today()
elif isinstance(start_date, datetime_):
start_date = start_date.date()
if end_date is None:
end_date = start_date
elif isinstance(end_date, datetime_):
end_date = end_date.date()
curs = currencies.get(territory.upper(), ())
# TODO: validate that the territory exists
def _is_active(start, end):
return (start is None or start <= end_date) and \
(end is None or end >= start_date)
result = []
for currency_code, start, end, is_tender in curs:
if start:
start = date_(*start)
if end:
end = date_(*end)
if ((is_tender and tender) or
(not is_tender and non_tender)) and _is_active(start, end):
if include_details:
result.append({
'currency': currency_code,
'from': start,
'to': end,
'tender': is_tender,
})
else:
result.append(currency_code)
return result
示例13: format_currency
def format_currency(number, currency, format=None, locale=LC_NUMERIC,
currency_digits=True, format_type='standard'):
u"""Return formatted currency value.
>>> format_currency(1099.98, 'USD', locale='en_US')
u'$1,099.98'
>>> format_currency(1099.98, 'USD', locale='es_CO')
u'US$\\xa01.099,98'
>>> format_currency(1099.98, 'EUR', locale='de_DE')
u'1.099,98\\xa0\\u20ac'
The format can also be specified explicitly. The currency is
placed with the '¤' sign. As the sign gets repeated the format
expands (¤ being the symbol, ¤¤ is the currency abbreviation and
¤¤¤ is the full name of the currency):
>>> format_currency(1099.98, 'EUR', u'\xa4\xa4 #,##0.00', locale='en_US')
u'EUR 1,099.98'
>>> format_currency(1099.98, 'EUR', u'#,##0.00 \xa4\xa4\xa4', locale='en_US')
u'1,099.98 euros'
Currencies usually have a specific number of decimal digits. This function
favours that information over the given format:
>>> format_currency(1099.98, 'JPY', locale='en_US')
u'\\xa51,100'
>>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES')
u'1.100'
However, the number of decimal digits can be overriden from the currency
information, by setting the last parameter to ``False``:
>>> format_currency(1099.98, 'JPY', locale='en_US', currency_digits=False)
u'\\xa51,099.98'
>>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES', currency_digits=False)
u'1.099,98'
If a format is not specified the type of currency format to use
from the locale can be specified:
>>> format_currency(1099.98, 'EUR', locale='en_US', format_type='standard')
u'\\u20ac1,099.98'
When the given currency format type is not available, an exception is
raised:
>>> format_currency('1099.98', 'EUR', locale='root', format_type='unknown')
Traceback (most recent call last):
...
UnknownCurrencyFormatError: "'unknown' is not a known currency format type"
:param number: the number to format
:param currency: the currency code
:param format: the format string to use
:param locale: the `Locale` object or locale identifier
:param currency_digits: use the currency's number of decimal digits
:param format_type: the currency format type to use
"""
locale = Locale.parse(locale)
if format:
pattern = parse_pattern(format)
else:
try:
pattern = locale.currency_formats[format_type]
except KeyError:
raise UnknownCurrencyFormatError("%r is not a known currency format"
" type" % format_type)
if currency_digits:
fractions = get_global('currency_fractions')
try:
digits = fractions[currency][0]
except KeyError:
digits = fractions['DEFAULT'][0]
frac = (digits, digits)
else:
frac = None
return pattern.apply(number, locale, currency=currency, force_frac=frac)
示例14: test_get_global
def test_get_global():
assert core.get_global('zone_aliases')['UTC'] == 'Etc/GMT'
assert core.get_global('zone_territories')['Europe/Berlin'] == 'DE'
示例15: get_global
except ImportError:
try:
import winreg
except ImportError:
winreg = None
from babel.core import get_global
import pytz
# When building the cldr data on windows this module gets imported.
# Because at that point there is no global.dat yet this call will
# fail. We want to catch it down in that case then and just assume
# the mapping was empty.
try:
tz_names = get_global('windows_zone_mapping')
except RuntimeError:
tz_names = {}
def valuestodict(key):
"""Convert a registry key's values to a dictionary."""
dict = {}
size = winreg.QueryInfoKey(key)[1]
for i in range(size):
data = winreg.EnumValue(key, i)
dict[data[0]] = data[1]
return dict
def get_localzone_name():