15.2 locale:文化本地化API
locale模块是Python国际化和本地化支持库的一部分。它提供了一种标准方法,可以处理可能依赖于语言或用户位置的操作。例如,它会将数字格式化为货币形式,比较字符串以完成排序,并且还会处理日期。它不涉及转换(见gettext模块)或Unicode编码(见codecs模块)。
说明:改变本地化环境可能会对整个应用来影响,所以推荐的实践做法是避免改变库中的值,而是让应用一次性设置。在这一节的例子中,会在一个小程序中多次改变本地化环境,以强调不同本地化环境设置的差别。通常更常见的情况是由应用在启动时设置一次本地化环境,或者在接收到一个Web请求时设置一次本地化环境,而不会反复改变。
这一节将介绍locale模块中的一些高级函数。其他函数则为低级函数(format_string())或者与管理应用的本地化环境有关(resetlocale())。
15.2.1 探查当前本地化环境
要让用户改变应用的本地化环境设置,最常见的方式是通过一个环境变量(LC_ALL,LC_CTYPE,LANG或LANGUAGE,这取决于使用哪个平台)。然后应用调用setlocale()而不是指定硬编码的值,并且还会使用环境值。
import locale
import os
import pprint
# Default settings based on the user's environment
locale.setlocale(locale.LC_ALL,'')
print('Environment settings:')
for env_name in ['LC_ALL','LC_TCYPE','LANG','LANGUAGE']:
print(' {} = {}'.format(
env_name,os.environ.get(env_name,''))
)
# What is the locale?
print('\nLocale from environment:',locale.getlocale())
template = """
Numeric formattting:
Decimal point : "{decimal_point}"
Grouping positions : {grouping}
Thousands separator : "{thousands_sep}"
Monetary formatting:
International currency symbol : "{int_curr_symbol!r}"
Local currency symbol : {currency_symbol!r}
Symbol precedes positive value : {p_cs_precedes}
Symbol precedes negative value : {n_cs_precedes}
Decimal point : "{mon_decimal_point}"
Digits in fractional values : {frac_digits}
Digits in fractional values,
international : {int_frac_digits}
Grouping positions : {mon_grouping}
Thousands separator : "{mon_thousands_sep}"
Positive sign : "{positive_sign}"
Positive sign position : {p_sign_posn}
Negative sign : "{negative_sign}"
Negative sign position : {n_sign_posn}
"""
sign_positions = {
0: 'Surrounded by parentheses',
1: 'Before value and symbol',
2: 'After value and symbol',
3: 'Before value',
4: 'After value',
locale.CHAR_MAX: 'Unspecified',
}
info = {}
info.update(locale.localeconv())
info['p_sign_posn'] = sign_positions[info['p_sign_posn']]
info['n_sign_posn'] = sign_positions[info['n_sign_posn']]
print(template.format(**info))
localeconv()方法返回一个字典,其中包含本地化环境的约定。标准库文档中给出了完整的值名和定义。