gpt4 book ai didi

python - locale.getpreferredencoding() - 为什么这会重置 string.letters?

转载 作者:IT老高 更新时间:2023-10-28 21:13:26 25 4
gpt4 key购买 nike

>>> import string
>>> import locale
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> locale.getpreferredencoding()
'UTF-8'
>>> string.letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'

有什么解决方法吗?

平台:LinuxPython2.6.7 和 Python2.7.3 似乎受到影响,在 Python3 中运行良好(使用 ascii_letters)

最佳答案

注意:OP 解决问题的方法是将 encoding='UTF-8' 传递给 open 调用。如果您遇到此问题并且只是在寻找解决方法,则此方法有效。这篇文章的其余部分强调为什么


会发生什么

正如 Lukas 所说,文档指定:

On some systems, it is necessary to invoke setlocale() to obtain the user preferences

最初,string.letters 设置为返回 lowercase + uppercase:

lowercase = 'abcdefghijklmnopqrstuvwxyz'
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
letters = lowercase + uppercase

但是,当您调用 getpreferredencoding() 时,_locale 模块会通过调用 PyDict_SetItemString(string, "letters", ulo); 来覆盖它;fixup_ulcase(void) 内生成它们之后,使用以下内容:

/* create letters string */
n = 0;
for (c = 0; c < 256; c++) {
if (isalpha(c))
ul[n++] = c;
}
ulo = PyString_FromStringAndSize((const char *)ul, n);
if (!ulo)
return;
if (string)
PyDict_SetItemString(string, "letters", ulo);
Py_DECREF(ulo);

反过来,这在 PyLocale_setlocale 中调用,这确实是 setlocale,由 getpreferredencoding 调用 - 这里的代码 http://hg.python.org/cpython/file/07a6fca7ff42/Lib/locale.py#l612 :

  def getpreferredencoding(do_setlocale = True):
"""Return the charset that the user is likely using,
according to the system configuration."""
if do_setlocale:
oldloc = setlocale(LC_CTYPE)
try:
setlocale(LC_CTYPE, "")
except Error:
pass
result = nl_langinfo(CODESET)
setlocale(LC_CTYPE, oldloc)
return result
else:
return nl_langinfo(CODESET)

如何避免?

试试getpreferredencoding(False)

为什么在 Windows 中不会发生?

Windows 使用不同的代码来获取语言环境,如您所见 here .

在 Python 3 中

在 Python 3 中,getdefaultlocale 不接受 bool setlocale 变量,也不调用 setlocale 本身,如您所见 here .

关于python - locale.getpreferredencoding() - 为什么这会重置 string.letters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23743160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com