gpt4 book ai didi

python - 在 Windows 中处理 unicode 字符串

转载 作者:行者123 更新时间:2023-11-28 21:28:55 25 4
gpt4 key购买 nike

我第一次在 Windows (Vista) 上尝试我的一个 Python 脚本,它处理 unicode 字符,但发现它无法正常工作。该脚本在 Linux 和 OS X 上运行良好,但在 Windows 上运行不佳。这是我试过的小脚本:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, sys, codecs

reload(sys)
sys.setdefaultencoding('utf-8')
print "\nDefault encoding\t: %s" % sys.getdefaultencoding()
print "sys.stdout.encoding\t: %s\n" % sys.stdout.encoding

## Unicode strings
ln1 = u"?0>9<8~7|65\"4:3}2{1+_)(*&^%$£@!/`\\][=-"
ln2 = u"mnbvc xzasdfghjkl;'poiuyàtrewq€é#¢."

refStr = u"%s%s" % (ln2,ln1)
print "refSTR: ", refStr

for x in refStr:
print "%s => %s" % (x, ord(u"%s" % x))

当我从 Windows CLI 运行脚本时,出现此错误:

C:\Users\san\Scripts>python uniCode.py

Default encoding : utf-8
sys.stdout.encoding : cp850

refSTR; Traceback (most recent call last):
File "uniCode.py", line 18, in <module>
print "refSTR; ", refStr
File "C:\Python27\lib\encodings\cp850.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u20ac' in position
30: character maps to <undefined>

我遇到了 this Python-wiki并从那里尝试了一些东西,但没有用。有谁知道我还缺少什么?非常感谢任何帮助。干杯!!

最佳答案

Windows 控制台有一个 Unicode API,但没有 utf-8。 Python 试图将 Unicode 字符编码为您的控制台的 8 位代码页 cp850,这显然行不通。 Windows 控制台中应该有一个支持 utf-8 的代码页 (chcp 65001),但它已严重损坏。阅读issue 1602并查看 sys_write_stdout.patchunicode2.py,它们使用 Unicode 宽字符函数,例如 WriteConsoleOutputWWriteConsoleW .不幸的是,这是一个低优先级的问题。

仅供引用,您还可以使用 IDLE 或其他 GUI 控制台(基于 pythonw.exe)来运行输出 Unicode 字符的脚本。例如:

C:\pythonXX\Lib\idlelib\idle.pyw -r script.py

但如果您需要编写 CLI 控制台工具,这不是一个通用的解决方案。

关于python - 在 Windows 中处理 unicode 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6788158/

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