我第一次尝试使用我的一个Python脚本处理Windows(Vista)上的unicode字符,并发现它不起作用。该脚本在Linux和OS X上运行得非常好,但在Windows上没有任何喜悦。这里是我试过的小脚本:在Windows中处理unicode字符串
#!/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运行命令行脚本,我得到这个错误:
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字节和字节。 –