【发布时间】:2011-07-22 09:35:41
【问题描述】:
第一次,我在 Windows (Vista) 上尝试了一个处理 unicode 字符的 Python 脚本,但发现它不起作用。该脚本在 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 并从那里尝试了一些东西,但没有奏效。有人知道我还缺少什么吗?非常感谢任何帮助。干杯!!
【问题讨论】:
-
这是从 Python 3 开始可能有意义的一件事,它比 Python 2 更清楚 unicode 与字节。