localeInternationalization services国际化服务

Source code: Lib/locale.py


The locale module opens access to the POSIX locale database and functionality. locale模块打开对POSIX语言环境数据库和功能的访问。The POSIX locale mechanism allows programmers to deal with certain cultural issues in an application, without requiring the programmer to know all the specifics of each country where the software is executed.POSIX语言环境机制允许程序员处理应用程序中的某些文化问题,而不需要程序员了解执行软件的每个国家的所有细节。

The locale module is implemented on top of the _locale module, which in turn uses an ANSI C locale implementation if available.locale模块是在_locale模块之上实现的,该模块反过来使用ANSI C语言环境实现(如果可用)。

The locale module defines the following exception and functions:locale模块定义以下异常和函数:

exceptionlocale.Error

Exception raised when the locale passed to setlocale() is not recognized.无法识别传递给setlocale()的区域设置时引发异常。

locale.setlocale(category, locale=None)

If locale is given and not None, setlocale() modifies the locale setting for the category. 如果给定了locale而不是None,则setlocale()修改类别的区域设置。The available categories are listed in the data description below. 以下数据描述中列出了可用类别。locale may be a string, or an iterable of two strings (language code and encoding). locale可以是一个字符串,也可以是两个字符串(语言代码和编码)的可迭代对象。If it’s an iterable, it’s converted to a locale name using the locale aliasing engine. 如果它是iterable,则使用区域设置别名引擎将其转换为区域设置名称。An empty string specifies the user’s default settings. 空字符串指定用户的默认设置。If the modification of the locale fails, the exception Error is raised. 如果区域设置修改失败,则会引发异常ErrorIf successful, the new locale setting is returned.如果成功,则返回新的区域设置。

If locale is omitted or None, the current setting for category is returned.如果忽略locale或为None,则返回类别的当前设置。

setlocale() is not thread-safe on most systems. 在大多数系统上不是线程安全的。Applications typically start with a call of应用程序通常用以下方式开始调用

import locale
locale.setlocale(locale.LC_ALL, '')

This sets the locale for all categories to the user’s default setting (typically specified in the LANG environment variable). 这会将所有类别的区域设置设置为用户的默认设置(通常在LANG环境变量中指定)。If the locale is not changed thereafter, using multithreading should not cause problems.如果此后没有更改区域设置,则使用多线程不会导致问题。

locale.localeconv()

Returns the database of the local conventions as a dictionary. 将本地约定的数据库作为字典返回。This dictionary has the following strings as keys:此词典具有以下字符串作为键:

Category类别

Key

Meaning含义

LC_NUMERIC

'decimal_point'

Decimal point character.小数点字符。

'grouping'

Sequence of numbers specifying which relative positions the 'thousands_sep' is expected. 数字序列,指定预期的'thousands_sep'的相对位置。If the sequence is terminated with CHAR_MAX, no further grouping is performed. 如果序列以CHAR_MAX终止,则不执行进一步分组。If the sequence terminates with a 0, the last group size is repeatedly used.如果序列以0终止,则重复使用最后一个组大小。

'thousands_sep'

Character used between groups.组之间使用的字符。

LC_MONETARY

'int_curr_symbol'

International currency symbol.国际货币符号。

'currency_symbol'

Local currency symbol.当地货币符号。

'p_cs_precedes/n_cs_precedes'

Whether the currency symbol precedes the value (for positive resp. negative values).货币符号是否在值之前(正值或负值)。

'p_sep_by_space/n_sep_by_space'

Whether the currency symbol is separated from the value by a space (for positive resp. negative values).货币符号是否用空格与值分隔(正值和负值)。

'mon_decimal_point'

Decimal point used for monetary values.用于货币值的小数点。

'frac_digits'

Number of fractional digits used in local formatting of monetary values.货币值的本地格式中使用的小数位数。

'int_frac_digits'

Number of fractional digits used in international formatting of monetary values.货币值国际格式中使用的小数位数。

'mon_thousands_sep'

Group separator used for monetary values.用于货币值的组分隔符。

'mon_grouping'

Equivalent to 'grouping', used for monetary values.相当于'grouping',用于货币价值。

'positive_sign'

Symbol used to annotate a positive monetary value.用于注释正货币值的符号。

'negative_sign'

Symbol used to annotate a negative monetary value.用于注释负货币值的符号。

'p_sign_posn/n_sign_posn'

The position of the sign (for positive resp. negative values), see below.符号的位置(正值和负值),请参阅下文。

All numeric values can be set to CHAR_MAX to indicate that there is no value specified in this locale.所有数值都可以设置为CHAR_MAX,以指示此区域设置中没有指定值。

The possible values for 'p_sign_posn' and 'n_sign_posn' are given below.'p_sign_posn''n_sign_posn'的可能值如下所示。

Value

Explanation解释

0

Currency and value are surrounded by parentheses.货币和价值用括号括起来。

1

The sign should precede the value and currency symbol.符号应位于价值和货币符号之前。

2

The sign should follow the value and currency symbol.符号应跟随价值和货币符号。

3

The sign should immediately precede the value.符号应紧跟在值之前。

4

The sign should immediately follow the value.符号应紧跟在值之后。

CHAR_MAX

Nothing is specified in this locale.在此区域设置中未指定任何内容。

The function sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale or the LC_MONETARY locale if locales are different and numeric or monetary strings are non-ASCII. 如果区域设置不同,并且数字或货币字符串不是ASCII,则函数会将LC_CTYPE区域设置临时设置为LC_NUMERIC区域设置或LC_MONETARY区域设置。This temporary change affects other threads.此临时更改会影响其他线程。

Changed in version 3.7:版本3.7中更改: The function now sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale in some cases.在某些情况下,该函数现在将LC_CTYPE区域设置临时设置为LC_NUMERIC区域设置。

locale.nl_langinfo(option)

Return some locale-specific information as a string. 以字符串形式返回一些特定于区域设置的信息。This function is not available on all systems, and the set of possible options might also vary across platforms. 此功能并非在所有系统上都可用,可能的选项集也可能因平台而异。The possible argument values are numbers, for which symbolic constants are available in the locale module.可能的参数值是数字,在locale模块中可以使用符号常量。

The nl_langinfo() function accepts one of the following keys. nl_langinfo()函数接受以下键之一。Most descriptions are taken from the corresponding description in the GNU C library.大多数描述取自GNU C库中的相应描述。

locale.CODESET

Get a string with the name of the character encoding used in the selected locale.获取包含所选区域设置中使用的字符编码名称的字符串。

locale.D_T_FMT

Get a string that can be used as a format string for time.strftime() to represent date and time in a locale-specific way.获取一个字符串,该字符串可以用作time.strftime()的格式字符串,以特定于区域设置的方式表示日期和时间。

locale.D_FMT

Get a string that can be used as a format string for time.strftime() to represent a date in a locale-specific way.获取一个字符串,该字符串可以用作time.strftime()的格式字符串,以特定于区域设置的方式表示日期。

locale.T_FMT

Get a string that can be used as a format string for time.strftime() to represent a time in a locale-specific way.获取一个字符串,该字符串可以用作time.strftime()的格式字符串,以特定于区域设置的方式表示时间。

locale.T_FMT_AMPM

Get a format string for time.strftime() to represent time in the am/pm format.获取time.strftime()的格式字符串,以am/pm格式表示时间。

DAY_1 ... DAY_7

Get the name of the n-th day of the week.获取一周中第n天的名称。

Note

This follows the US convention of DAY_1 being Sunday, not the international convention (ISO 8601) that Monday is the first day of the week.这遵循了美国将DAY_1定为星期日的惯例,而不是将星期一定为一周的第一天的国际惯例(ISO 8601)。

ABDAY_1 ... ABDAY_7

Get the abbreviated name of the n-th day of the week.获取一周中第n天的缩写名称。

MON_1 ... MON_12

Get the name of the n-th month.获取第n个月的名称。

ABMON_1 ... ABMON_12

Get the abbreviated name of the n-th month.获取第n个月的缩写名称。

locale.RADIXCHAR

Get the radix character (decimal dot, decimal comma, etc.).获取基数字符(小数点、小数逗号等)。

locale.THOUSEP

Get the separator character for thousands (groups of three digits).获取数千的分隔符(三位数组)。

locale.YESEXPR

Get a regular expression that can be used with the regex function to recognize a positive response to a yes/no question.获取一个正则表达式,该表达式可以与正则表达式函数一起使用,以识别对是/否问题的肯定响应。

Note

The expression is in the syntax suitable for the regex() function from the C library, which might differ from the syntax used in re.该表达式的语法适用于C库中的regex()函数,这可能与re中使用的语法不同。

locale.NOEXPR

Get a regular expression that can be used with the regex(3) function to recognize a negative response to a yes/no question.获取可与正则表达式(3)函数一起使用的正则表达式,以识别对是/否问题的否定响应。

locale.CRNCYSTR

Get the currency symbol, preceded by “-” if the symbol should appear before the value, “+” if the symbol should appear after the value, or “.” if the symbol should replace the radix character.如果符号应出现在值之前,则获取货币符号,如果符号应出现在值之后,则获取“+”,如果符号应替换基数字符,则获取“.”。

locale.ERA

Get a string that represents the era used in the current locale.获取表示当前区域设置中使用的era的字符串。

Most locales do not define this value. 大多数地区不定义此值。An example of a locale which does define this value is the Japanese one. 定义此值的区域设置示例是日语。In Japan, the traditional representation of dates includes the name of the era corresponding to the then-emperor’s reign.在日本,日期的传统表示包括与当时的皇帝统治相对应的时代名称。

Normally it should not be necessary to use this value directly. 通常不需要直接使用该值。Specifying the E modifier in their format strings causes the time.strftime() function to use this information. 在格式字符串中指定E修饰符会导致time.strftime()函数使用此信息。The format of the returned string is not specified, and therefore you should not assume knowledge of it on different systems.返回字符串的格式没有指定,因此您不应该假设在不同的系统上知道它。

locale.ERA_D_T_FMT

Get a format string for time.strftime() to represent date and time in a locale-specific era-based way.获取time.strftime()的格式字符串,以基于区域设置特定时代的方式表示日期和时间。

locale.ERA_D_FMT

Get a format string for time.strftime() to represent a date in a locale-specific era-based way.获取time.strftime()的格式字符串,以基于区域设置特定时代的方式表示日期。

locale.ERA_T_FMT

Get a format string for time.strftime() to represent a time in a locale-specific era-based way.获取time.strftime()的格式字符串,以基于区域设置特定时代的方式表示时间。

locale.ALT_DIGITS

Get a representation of up to 100 values used to represent the values 0 to 99.获取最多100个值的表示,用于表示0到99的值。

locale.getdefaultlocale([envvars])

Tries to determine the default locale settings and returns them as a tuple of the form (language code, encoding).尝试确定默认的区域设置,并将其作为(language code, encoding)形式的元组返回。

According to POSIX, a program which has not called setlocale(LC_ALL, '') runs using the portable 'C' locale. Calling setlocale(LC_ALL, '') lets it use the default locale as defined by the LANG variable. Since we do not want to interfere with the current locale setting we thus emulate the behavior in the way described above.

To maintain compatibility with other platforms, not only the LANG variable is tested, but a list of variables given as envvars parameter. The first found to be defined will be used. envvars defaults to the search path used in GNU gettext; it must always contain the variable name 'LANG'. The GNU gettext search path contains 'LC_ALL', 'LC_CTYPE', 'LANG' and 'LANGUAGE', in that order.

Except for the code 'C', the language code corresponds to RFC 1766. language code and encoding may be None if their values cannot be determined.

locale.getlocale(category=LC_CTYPE)

Returns the current setting for the given locale category as sequence containing language code, encoding. category may be one of the LC_* values except LC_ALL. It defaults to LC_CTYPE.

Except for the code 'C', the language code corresponds to RFC 1766. language code and encoding may be None if their values cannot be determined.

locale.getpreferredencoding(do_setlocale=True)

Return the locale encoding used for text data, according to user preferences. User preferences are expressed differently on different systems, and might not be available programmatically on some systems, so this function only returns a guess.

On some systems, it is necessary to invoke setlocale() to obtain the user preferences, so this function is not thread-safe. If invoking setlocale is not necessary or desired, do_setlocale should be set to False.

On Android or if the Python UTF-8 Mode is enabled, always return 'UTF-8', the locale encoding and the do_setlocale argument are ignored.

The Python preinitialization configures the LC_CTYPE locale. See also the filesystem encoding and error handler.

Changed in version 3.7:版本3.7中更改: The function now always returns UTF-8 on Android or if the Python UTF-8 Mode is enabled.现在,如果启用了Python UTF-8模式,该函数在Android上总是返回UTF-8

locale.normalize(localename)

Returns a normalized locale code for the given locale name. The returned locale code is formatted for use with setlocale(). If normalization fails, the original name is returned unchanged.

If the given encoding is not known, the function defaults to the default encoding for the locale code just like setlocale().

locale.resetlocale(category=LC_ALL)

Sets the locale for category to the default setting.

The default setting is determined by calling getdefaultlocale(). category defaults to LC_ALL.

locale.strcoll(string1, string2)

Compares two strings according to the current LC_COLLATE setting. As any other compare function, returns a negative, or a positive value, or 0, depending on whether string1 collates before or after string2 or is equal to it.

locale.strxfrm(string)

Transforms a string to one that can be used in locale-aware comparisons. For example, strxfrm(s1) < strxfrm(s2) is equivalent to strcoll(s1, s2) < 0. This function can be used when the same string is compared repeatedly, e.g. when collating a sequence of strings.

locale.format_string(format, val, grouping=False, monetary=False)

Formats a number val according to the current LC_NUMERIC setting. The format follows the conventions of the % operator. For floating point values, the decimal point is modified if appropriate. If grouping is true, also takes the grouping into account.

If monetary is true, the conversion uses monetary thousands separator and grouping strings.

Processes formatting specifiers as in format % val, but takes the current locale settings into account.format % val处理格式说明符,但考虑当前区域设置。

Changed in version 3.7:版本3.7中更改: The monetary keyword parameter was added.

locale.format(format, val, grouping=False, monetary=False)

Please note that this function works like format_string() but will only work for exactly one %char specifier. For example, '%f' and '%.0f' are both valid specifiers, but '%f KiB' is not.

For whole format strings, use format_string().对于全格式字符串,请使用format_string()

Deprecated since version 3.7: Use format_string() instead.

locale.currency(val, symbol=True, grouping=False, international=False)

Formats a number val according to the current LC_MONETARY settings.

The returned string includes the currency symbol if symbol is true, which is the default. If grouping is true (which is not the default), grouping is done with the value. If international is true (which is not the default), the international currency symbol is used.

Note that this function will not work with the ‘C’ locale, so you have to set a locale via setlocale() first.

locale.str(float)

Formats a floating point number using the same format as the built-in function str(float), but takes the decimal point into account.

locale.delocalize(string)

Converts a string into a normalized number string, following the LC_NUMERIC settings.

New in version 3.5.版本3.5中新增。

locale.localize(string, grouping=False, monetary=False)

Converts a normalized number string into a formatted string following the LC_NUMERIC settings.

New in version 3.10.版本3.10中新增。

locale.atof(string, func=float)

Converts a string to a number, following the LC_NUMERIC settings, by calling func on the result of calling delocalize() on string.

locale.atoi(string)

Converts a string to an integer, following the LC_NUMERIC conventions.根据LC_NUMERIC惯例将字符串转换为整数。

locale.LC_CTYPE

Locale category for the character type functions. 字符类型函数的区域设置类别。Depending on the settings of this category, the functions of module string dealing with case change their behaviour.

locale.LC_COLLATE

Locale category for sorting strings. The functions strcoll() and strxfrm() of the locale module are affected.

locale.LC_TIME

Locale category for the formatting of time. 时间格式的区域设置类别。The function time.strftime() follows these conventions.

locale.LC_MONETARY

Locale category for formatting of monetary values. 货币值格式的区域设置类别。The available options are available from the localeconv() function.

locale.LC_MESSAGES

Locale category for message display. Python currently does not support application specific locale-aware messages. 消息显示的区域设置类别。Python目前不支持特定于应用程序的区域设置感知消息。Messages displayed by the operating system, like those returned by os.strerror() might be affected by this category.

locale.LC_NUMERIC

Locale category for formatting numbers. The functions format(), atoi(), atof() and str() of the locale module are affected by that category. All other numeric formatting operations are not affected.

locale.LC_ALL

Combination of all locale settings. If this flag is used when the locale is changed, setting the locale for all categories is attempted. 所有区域设置的组合。如果在更改区域设置时使用此标志,则尝试为所有类别设置区域设置。If that fails for any category, no category is changed at all. 如果这对任何类别都不起作用,那么就根本不会更改任何类别。When the locale is retrieved using this flag, a string indicating the setting for all categories is returned. 使用此标志检索区域设置时,将返回一个字符串,指示所有类别的设置。This string can be later used to restore the settings.此字符串稍后可用于恢复设置。

locale.CHAR_MAX

This is a symbolic constant used for different values returned by localeconv().

Example:

>>> import locale
>>> loc = locale.getlocale() # get current locale
# use German locale; name might vary with platform
>>> locale.setlocale(locale.LC_ALL, 'de_DE')
>>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut
>>> locale.setlocale(locale.LC_ALL, '') # use user's preferred locale
>>> locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale
>>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale

Background, details, hints, tips and caveats背景、细节、提示、提示和注意事项

The C standard defines the locale as a program-wide property that may be relatively expensive to change. C标准将区域设置定义为程序范围内的属性,更改该属性可能相对昂贵。On top of that, some implementations are broken in such a way that frequent locale changes may cause core dumps. 除此之外,一些实现被破坏,频繁的区域设置更改可能会导致核心转储。This makes the locale somewhat painful to use correctly.这使得正确使用区域设置有些困难。

Initially, when a program is started, the locale is the C locale, no matter what the user’s preferred locale is. There is one exception: the LC_CTYPE category is changed at startup to set the current locale encoding to the user’s preferred locale encoding. The program must explicitly say that it wants the user’s preferred locale settings for other categories by calling setlocale(LC_ALL, '').

It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program. 在某些库例程中调用setlocale()通常是个坏主意,因为它会影响整个程序。Saving and restoring it is almost as bad: it is expensive and affects other threads that happen to run before the settings have been restored.保存和恢复它几乎同样糟糕:它很昂贵,并且会影响在恢复设置之前运行的其他线程。

If, when coding a module for general use, you need a locale independent version of an operation that is affected by the locale (such as certain formats used with time.strftime()), you will have to find a way to do it without using the standard library routine. Even better is convincing yourself that using locale settings is okay. 更好的是说服自己使用区域设置是可以的。Only as a last resort should you document that your module is not compatible with non-C locale settings.只有在万不得已的情况下,您才应该记录您的模块与非C语言环境设置不兼容。

The only way to perform numeric operations according to the locale is to use the special functions defined by this module: atof(), atoi(), format(), str().

There is no way to perform case conversions and character classifications according to the locale. 无法根据区域设置执行大小写转换和字符分类。For (Unicode) text strings these are done according to the character value only, while for byte strings, the conversions and classifications are done according to the ASCII value of the byte, and bytes whose high bit is set (i.e., non-ASCII bytes) are never converted or considered part of a character class such as letter or whitespace.对于(Unicode)文本字符串,这些仅根据字符值完成,而对于字节字符串,转换和分类根据字节的ASCII值完成,并且高位设置的字节(即非ASCII字节)从不转换或被视为字符类的一部分,如字母或空白。

For extension writers and programs that embed Python适用于嵌入Python的扩展编写器和程序

Extension modules should never call setlocale(), except to find out what the current locale is. But since the return value can only be used portably to restore it, that is not very useful (except perhaps to find out whether or not the locale is C).

When Python code uses the locale module to change the locale, this also affects the embedding application. If the embedding application doesn’t want this to happen, it should remove the _locale extension module (which does all the work) from the table of built-in modules in the config.c file, and make sure that the _locale module is not accessible as a shared library.

Access to message catalogs访问邮件目录

locale.gettext(msg)
locale.dgettext(domain, msg)
locale.dcgettext(domain, msg, category)
locale.textdomain(domain)
locale.bindtextdomain(domain, dir)

The locale module exposes the C library’s gettext interface on systems that provide this interface. locale模块在提供此接口的系统上公开C库的gettext接口。It consists of the functions gettext(), dgettext(), dcgettext(), textdomain(), bindtextdomain(), and bind_textdomain_codeset(). These are similar to the same functions in the gettext module, but use the C library’s binary format for message catalogs, and the C library’s search algorithms for locating message catalogs.

Python applications should normally find no need to invoke these functions, and should use gettext instead. A known exception to this rule are applications that link with additional C libraries which internally invoke gettext() or dcgettext(). For these applications, it may be necessary to bind the text domain, so that the libraries can properly locate their message catalogs.对于这些应用程序,可能需要绑定文本域,以便库可以正确定位其消息目录。