locale — 국제화 서비스

소스 코드: Lib/locale.py


locale 모듈은 POSIX 로케일 데이터베이스와 기능에 대한 액세스를 엽니다. POSIX 로케일 메커니즘은 프로그래머가 소프트웨어가 실행되는 국가별로 모든 세부 사항을 알 필요 없이 응용 프로그램에서 특정 문화적 문제를 다룰 수 있도록 합니다.

The locale module is implemented on top of the _locale module, which in turn uses an ANSI C locale implementation if available.

locale 모듈은 다음 예외와 함수를 정의합니다:

exception locale.Error

setlocale()에 전달된 로케일이 인식되지 않을 때 발생하는 예외.

locale.setlocale(category, locale=None)

locale이 제공되고 None이 아니면, setlocale()category의 로케일 설정을 수정합니다. 사용 가능한 범주는 아래 데이터 설명에 나열되어 있습니다. locale은 문자열이거나 두 개의 문자열(언어 코드와 인코딩)의 이터러블일 수 있습니다. 이터러블이면, 로케일 에일리어싱 엔진을 사용하여 로케일 이름으로 변환됩니다. 빈 문자열은 사용자의 기본 설정을 지정합니다. 로케일 수정에 실패하면, 예외 Error가 발생합니다. 성공하면, 새 로케일 설정이 반환됩니다.

locale이 생략되거나 None이면, category의 현재 설정이 반환됩니다.

setlocale()은 대부분의 시스템에서 스레드 안전하지 않습니다. 응용 프로그램은 보통 다음과 같은 호출로 시작합니다

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

이는 모든 범주의 로케일을 사용자의 기본 설정(보통 LANG 환경 변수에서 지정됩니다)으로 설정합니다. 그 후에 로케일을 변경하지 않으면, 다중 스레딩을 사용해도 문제가 발생하지 않습니다.

locale.localeconv()

현지 규칙의 데이터베이스를 딕셔너리로 반환합니다. 이 딕셔너리에는 키로 다음 문자열이 있습니다:

범주

의미

LC_NUMERIC

'decimal_point'

십진수 소수점 문자.

'grouping'

'thousands_sep'가 예상되는 상대 위치를 지정하는 숫자의 시퀀스. 시퀀스가 CHAR_MAX로 종료되면, 더 이상의 그룹화가 수행되지 않습니다. 시퀀스가 0으로 종료되면, 마지막 그룹 크기가 반복적으로 사용됩니다.

'thousands_sep'

그룹 간에 사용되는 문자.

LC_MONETARY

'int_curr_symbol'

국제 통화 기호.

'currency_symbol'

현지 통화 기호.

'p_cs_precedes/n_cs_precedes'

통화 기호가 값 앞에 오는지 여부 (각각 양과 음의 값).

'p_sep_by_space/n_sep_by_space'

통화 기호가 스페이스로 값과 구분되는지 여부 (각각 양과 음의 값).

'mon_decimal_point'

화폐값에 사용되는 십진수 소수점.

'frac_digits'

화폐값의 현지 형식에 사용되는 소수점 이하 자릿수.

'int_frac_digits'

화폐값의 국제 형식에 사용되는 소수점 이하 자릿수.

'mon_thousands_sep'

화폐값에 사용되는 그룹 구분자.

'mon_grouping'

'grouping'과 동등합니다, 화폐값에 사용됩니다.

'positive_sign'

양의 화폐값을 표현하는 데 사용되는 기호.

'negative_sign'

음의 화폐값을 표현하는 데 사용되는 기호.

'p_sign_posn/n_sign_posn'

부호의 위치 (각각 양과 음의 값), 아래를 참조하십시오.

모든 숫자 값은 이 로케일에서 아무런 값도 지정되지 않았음을 나타내는 CHAR_MAX로 설정할 수 있습니다.

'p_sign_posn''n_sign_posn'에 가능한 값은 다음과 같습니다.

설명

0

통화와 값을 괄호로 묶습니다.

1

부호는 값과 통화 기호 앞에 와야 합니다.

2

부호는 값과 통화 기호 뒤에 와야 합니다.

3

부호는 값 바로 앞에 와야 합니다.

4

부호는 값 바로 뒤에 와야 합니다.

CHAR_MAX

이 로케일에 지정된 것이 없습니다.

The function temporarily sets 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. This temporary change affects other threads.

버전 3.7에서 변경: The function now temporarily sets the LC_CTYPE locale to the LC_NUMERIC locale in some cases.

locale.nl_langinfo(option)

로케일 특정 정보를 문자열로 반환합니다. 이 함수를 모든 시스템에서 사용할 수 있는 것은 아니며, 가능한 옵션 집합은 플랫폼마다 다를 수 있습니다. 가능한 인자 값은 숫자이며, locale 모듈에 있는 기호 상수를 사용할 수 있습니다.

nl_langinfo() 함수는 다음 키 중 하나를 받아들입니다. 대부분의 설명은 GNU C 라이브러리의 해당 설명에서 가져옵니다.

locale.CODESET

선택한 로케일에 사용된 문자 인코딩의 이름으로 문자열을 가져옵니다.

locale.D_T_FMT

로케일 특정 방식으로 날짜와 시간을 표시하기 위해 time.strftime()의 포맷 문자열로 사용할 수 있는 문자열을 가져옵니다.

locale.D_FMT

로케일 특정 방식으로 날짜를 표시하기 위해 time.strftime()의 포맷 문자열로 사용할 수 있는 문자열을 가져옵니다.

locale.T_FMT

로케일 특정 방식으로 시간을 표시하기 위해 time.strftime()의 포맷 문자열로 사용할 수 있는 문자열을 가져옵니다.

locale.T_FMT_AMPM

am/pm 형식으로 시간을 나타내는 time.strftime()의 포맷 문자열을 가져옵니다.

locale.DAY_1
locale.DAY_2
locale.DAY_3
locale.DAY_4
locale.DAY_5
locale.DAY_6
locale.DAY_7

주의 n 번째 날의 이름을 가져옵니다.

참고

이것은 월요일이 주의 첫 번째 요일인 국제관례(ISO 8601)가 아니라, DAY_1이 일요일인 미국 관례를 따릅니다.

locale.ABDAY_1
locale.ABDAY_2
locale.ABDAY_3
locale.ABDAY_4
locale.ABDAY_5
locale.ABDAY_6
locale.ABDAY_7

주의 n 번째 날의 줄인 이름을 가져옵니다.

locale.MON_1
locale.MON_2
locale.MON_3
locale.MON_4
locale.MON_5
locale.MON_6
locale.MON_7
locale.MON_8
locale.MON_9
locale.MON_10
locale.MON_11
locale.MON_12

n 번째 달의 이름을 가져옵니다.

locale.ABMON_1
locale.ABMON_2
locale.ABMON_3
locale.ABMON_4
locale.ABMON_5
locale.ABMON_6
locale.ABMON_7
locale.ABMON_8
locale.ABMON_9
locale.ABMON_10
locale.ABMON_11
locale.ABMON_12

n 번째 달의 줄인 이름을 가져옵니다.

locale.RADIXCHAR

기수 문자(십진수 점, 십진수 쉼표, 등)를 가져옵니다.

locale.THOUSEP

천 단위 (3자리 그룹) 구분자 문자를 가져옵니다.

locale.YESEXPR

예/아니요 질문에 대한 긍정적인 응답을 인식하기 위해 regex 함수에 사용할 수 있는 정규식을 가져옵니다.

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.

참고

The regular expressions for YESEXPR and NOEXPR use syntax suitable for the regex function from the C library, which might differ from the syntax used in re.

locale.CRNCYSTR

통화 기호를 가져옵니다. 기호가 값 앞에 나타나야 하면 “-”, 기호가 값 뒤에 나타나야 하면 “+”, 또는 기호가 기수 문자를 대체해야 하면 “.”가 앞에 나옵니다.

locale.ERA

현재 로케일에 사용된 시대를 나타내는 문자열을 가져옵니다.

대부분의 로케일은 이 값을 정의하지 않습니다. 이 값을 정의하는 로케일의 예는 일본입니다. 일본에서, 전통적인 날짜 표시에는 당시 군주의 통치에 해당하는 시대의 이름이 포함됩니다.

일반적으로 이 값을 직접 사용할 필요는 없습니다. 포맷 문자열에 E 수정자를 지정하면 time.strftime() 함수가 이 정보를 사용합니다. 반환된 문자열의 형식은 지정되지 않습니다. 따라서 다른 시스템에서 이를 알고 있다고 가정해서는 안 됩니다.

locale.ERA_D_T_FMT

로케일 특정 시대 기반 방식으로 날짜와 시간을 나타내는 time.strftime()의 포맷 문자열을 가져옵니다.

locale.ERA_D_FMT

로케일 특정 시대 기반 방식으로 날짜를 나타내는 time.strftime()의 포맷 문자열을 가져옵니다.

locale.ERA_T_FMT

로케일 특정 시대 기반 방식으로 시간을 나타내는 time.strftime()의 포맷 문자열을 가져옵니다.

locale.ALT_DIGITS

0에서 99까지의 값을 나타내는 데 사용되는 최대 100개의 값의 표현을 가져옵니다.

locale.getdefaultlocale([envvars])

기본 로케일 설정을 판별하려고 시도하고 (language code, encoding) 형식의 튜플로 반환합니다.

POSIX에 따르면, setlocale(LC_ALL, '')을 호출하지 않은 프로그램은 이식성 있는 'C' 로케일을 사용하여 실행됩니다. setlocale(LC_ALL, '')을 호출하면 LANG 변수로 정의된 기본 로케일을 사용하도록 합니다. 현재 로케일 설정을 방해하고 싶지 않기 때문에 위에서 설명한 방식으로 동작을 에뮬레이트 합니다.

다른 플랫폼과의 호환성을 유지하기 위해, LANG 변수뿐만 아니라 envvars 매개 변수로 제공된 변수 리스트도 검사합니다. 가장 먼저 정의된 것으로 발견된 것이 사용됩니다. envvars는 GNU gettext에서 사용되는 검색 경로를 기본값으로 합니다; 항상 변수 이름 'LANG'을 포함해야 합니다. GNU gettext 검색 경로에는 'LC_ALL', 'LC_CTYPE', 'LANG''LANGUAGE'가 순서대로 포함됩니다.

코드 'C'를 제외하고, 언어 코드는 RFC 1766에 해당합니다. language codeencoding은 그 값을 판별할 수 없으면 None일 수 있습니다.

버전 3.11에서 폐지되었습니다, 버전 3.15에서 제거됩니다..

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.

코드 'C'를 제외하고, 언어 코드는 RFC 1766에 해당합니다. language codeencoding은 그 값을 판별할 수 없으면 None일 수 있습니다.

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.

일부 시스템에서는, 사용자 설정을 얻기 위해 setlocale()을 호출할 필요가 있어서, 이 함수는 스레드 안전하지 않습니다. setlocale을 호출할 필요가 없거나 원하지 않으면, do_setlocaleFalse로 설정해야 합니다.

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.

버전 3.7에서 변경: The function now always returns "utf-8" on Android or if the Python UTF-8 Mode is enabled.

locale.getencoding()

Get the current locale encoding:

  • On Android and VxWorks, return "utf-8".

  • On Unix, return the encoding of the current LC_CTYPE locale. Return "utf-8" if nl_langinfo(CODESET) returns an empty string: for example, if the current LC_CTYPE locale is not supported.

  • On Windows, return the ANSI code page.

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

This function is similar to getpreferredencoding(False) except this function ignores the Python UTF-8 Mode.

버전 3.11에 추가.

locale.normalize(localename)

주어진 로케일 이름에 대해 정규화된 로케일 코드를 반환합니다. 반환된 로케일 코드는 setlocale()에서 사용하도록 포맷됩니다. 정규화에 실패하면, 원래 이름이 변경되지 않은 상태로 반환됩니다.

주어진 인코딩이 알려지지 않았으면, 함수는 setlocale()처럼 로케일 코드의 기본 인코딩을 기본값으로 사용합니다.

locale.resetlocale(category=LC_ALL)

category의 로케일을 기본 설정으로 설정합니다.

기본 설정은 getdefaultlocale()을 호출하여 결정됩니다. category의 기본값은 LC_ALL입니다.

버전 3.11에서 폐지되었습니다, 버전 3.13에서 제거됩니다..

locale.strcoll(string1, string2)

현재 LC_COLLATE 설정에 따라 두 문자열을 비교합니다. 다른 비교 함수처럼, string1string2 앞이니 뒤에 오는지 또는 같은지에 따라 음수나 양수 값 또는 0을 반환합니다.

locale.strxfrm(string)

문자열을 로케일을 고려한 비교에 사용할 수 있는 문자열로 변환합니다. 예를 들어, strxfrm(s1) < strxfrm(s2)strcoll(s1, s2) < 0과 동등합니다. 이 함수는 같은 문자열이 반복적으로 비교될 때, 예를 들어 문자열 시퀀스를 정렬할 때, 사용할 수 있습니다.

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.

monetary가 참이면, 변환은 화폐 천 단위 구분 기호와 그룹화 문자열을 사용합니다.

format % val에서처럼 포맷 지정자를 처리하지만, 현재 로케일 설정을 고려합니다.

버전 3.7에서 변경: monetary 키워드 매개 변수가 추가되었습니다.

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

현재 LC_MONETARY 설정에 따라 숫자 val을 포맷합니다.

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.

참고

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

locale.str(float)

내장 함수 str(float)와 같은 형식을 사용하여 부동 소수점 숫자를 포맷하지만, 십진수 소수점을 고려합니다.

locale.delocalize(string)

LC_NUMERIC 설정에 따라, 문자열을 정규화된 숫자 문자열로 변환합니다.

버전 3.5에 추가.

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

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

버전 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)

LC_NUMERIC 규칙에 따라, 문자열을 정수로 변환합니다.

locale.LC_CTYPE

Locale category for the character type functions. Most importantly, this category defines the text encoding, i.e. how bytes are interpreted as Unicode codepoints. See PEP 538 and PEP 540 for how this variable might be automatically coerced to C.UTF-8 to avoid issues created by invalid settings in containers or incompatible settings passed over remote SSH connections.

Python doesn’t internally use locale-dependent character transformation functions from ctype.h. Instead, an internal pyctype.h provides locale-independent equivalents like Py_TOLOWER.

locale.LC_COLLATE

문자열 정렬을 위한 로케일 범주. locale 모듈의 함수 strcoll()strxfrm()이 영향을 받습니다.

locale.LC_TIME

시간 포매팅을 위한 로케일 범주. time.strftime() 함수는 이러한 규칙을 따릅니다.

locale.LC_MONETARY

화폐값의 포매팅을 위한 로케일 범주. 사용 가능한 옵션은 localeconv() 함수에서 제공됩니다.

locale.LC_MESSAGES

메시지 표시를 위한 로케일 범주. 파이썬은 현재 응용 프로그램에 특정한 로케일을 고려한 메시지를 지원하지 않습니다. os.strerror()에서 반환된 메시지처럼 운영 체제에서 표시되는 메시지는 이 범주의 영향을 받을 수 있습니다.

This value may not be available on operating systems not conforming to the POSIX standard, most notably Windows.

locale.LC_NUMERIC

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

locale.LC_ALL

모든 로케일 설정의 조합. 로케일을 변경할 때 이 플래그를 사용하면, 모든 범주에 대한 로케일 설정을 시도합니다. 어떤 범주에서 실패하면, 아무런 범주도 변경되지 않습니다. 이 플래그를 사용하여 로케일을 가져오면, 모든 범주의 설정을 나타내는 문자열이 반환됩니다. 이 문자열은 나중에 설정을 복원하는 데 사용할 수 있습니다.

locale.CHAR_MAX

이것은 localeconv()가 반환한 다른 값에 사용되는 기호 상수입니다.

예:

>>> 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

배경, 세부 사항, 힌트, 팁 및 경고

The C standard defines the locale as a program-wide property that may be relatively expensive to change. 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.

처음에, 프로그램이 시작할 때, 사용자가 선호하는 로케일이 무엇이든 로케일은 C 로케일입니다. 한 가지 예외가 있습니다: LC_CTYPE 범주는 시작 시 현재 로케일 인코딩을 사용자가 선호하는 로케일 인코딩으로 설정하도록 변경됩니다. 다른 범주에 대해서는 프로그램이 setlocale(LC_ALL, '')을 호출하여 사용자가 선호하는 로케일 설정을 원한다고 명시적으로 말해야 합니다.

일반적으로 어떤 라이브러리 루틴에서 setlocale()을 호출하는 것은 나쁜 생각입니다. 부작용으로 전체 프로그램에 영향을 미치기 때문입니다. 저장하고 복원하는 것도 거의 비슷하게 나쁩니다: 비용이 많이 들고 설정이 복원되기 전에 실행되는 다른 스레드에 영향을 줍니다.

일반적인 용도로 모듈을 코딩할 때, 로케일에 영향을 받는 로케일 독립적인 버전의 연산(가령 time.strftime()에 사용되는 특정 포맷)이 필요하면, 표준 라이브러리 루틴을 사용하지 않고 수행할 수 있는 방법을 찾아야 합니다. 로케일 설정을 사용하는 것이 좋다고 자신을 설득하는 것이 더 좋습니다. 최후의 수단으로만 모듈이 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_string(), str().

로케일에 따라 대소 문자 변환과 문자 분류를 수행할 방법이 없습니다. (유니코드) 텍스트 문자열의 경우 이것은 문자 값으로만 수행되는 반면, 바이트 문자열의 경우, 바이트의 ASCII 값에 따라 수행되고, 높은 비트가 설정된 바이트(즉, ASCII가 아닌 바이트)는 절대 변환되거나 글자나 공백과 같은 문자 클래스의 일부로 고려되지 않습니다.

확장 작성자와 파이썬을 내장하는 프로그램의 경우

확장 모듈은 현재 로케일이 무엇인지 찾는 것을 제외하고는 setlocale()을 호출해서는 안 됩니다. 그러나 반환 값은 이식성 있게 복원하는 데만 사용될 수 있기 때문에, 그다지 유용하지 않습니다 (아마도 로케일이 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.

메시지 카탈로그에 액세스

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

The locale module exposes the C library’s gettext interface on systems that provide this interface. 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 C functions 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.