在Windows上设置Python的语言环境的正确方法是什么?

时间:2009-06-05 13:56:43

标签: python windows localization internationalization

我正在尝试以区域设置感知的方式对字符串列表进行排序。我已经将Babel库用于其他与i18n相关的任务,但它不支持排序。 Python的locale模块提供了strcoll函数,但需要将进程的语言环境设置为我想要使用的语言环境。有点痛,但我可以忍受它。

问题是我似乎无法实际设置语言环境。 locale模块的documentation给出了这个示例:

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

当我跑步时,我明白了:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python26\Lib\locale.py", line 494, in setlocale
locale.Error: unsupported locale setting

我做错了什么?

6 个答案:

答案 0 :(得分:99)

好像你正在使用Windows。区域设置字符串在那里是不同的。更准确地看一下doc:

locale.setlocale(locale.LC_ALL, 'de_DE') # use German locale; name might vary with platform

在Windows上,我认为它会是这样的:

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

MSDN有language stringscountry/region strings

的列表

答案 1 :(得分:11)

你应该没有将明确的语言环境传递给setlocale,这是错误的。让它从环境中找出来。你必须传递一个空字符串

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

答案 2 :(得分:10)

这是在Windows上执行此操作的唯一方法(德语区域设置的示例):

import locale

locale.setlocale(category=locale.LC_ALL,
                 locale="German")  # Not locale="de_DE"

答案 3 :(得分:6)

Ubuntu的

在Ubuntu上,您可能遇到此问题,因为您的系统上没有安装本地。

从shell试试:

$> locale -a

并检查您是否找到了您感兴趣的区域设置。否则您必须安装它:

$> sudo apt-get install language-pack-XXX

其中XXX是您的语言(在我的情况下是“xxx = it”,意大利语语言环境) 然后运行dpkg-reconfigure

$> sudo dpkg-reconfigure locales

然后在你的python shell中再试一次:

>>> import locale
>>> locale.setlocale(locale.LC_ALL,'it_IT.UTF-8')

(这是意大利语语言环境,这是我需要的)

答案 4 :(得分:6)

我知道这已经在几年前被问过,但我想我会尝试在Windows上使用Python 3.6添加我发现的内容:

import locale
for x in locale.windows_locale.values():
    print(x.replace('_','-'))

我尝试了一些,这似乎也是一种查找,Windows上可用的内容的方法。

很高兴知道:由于某些原因,这与当前稳定版本的Python中的strptime()不兼容

然后你只需设置语言环境:

locale.setlocale(locale.LC_ALL, any_item_of_the_printed_strings)

答案 5 :(得分:3)

来自locale.setlocale docs:

locale.setlocale(category, locale=None):
    """
    Set the locale for the given category.  The locale can be
    a string, an iterable of two strings (language code and encoding),
    or None.
    """"

在Linux(尤其是Ubuntu)下,您可以使用

locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')

locale.setlocale(locale.LC_ALL, ('de', 'utf-8'))

如果系统上的区域设置未安装,您将收到相同的错误。因此,请确保您的系统上已安装语言环境

$ locale -a # to list the currently installed locales
$ (sudo) locale-gen de_DE.UTF-8 # to install new locale
相关问题