如何在命令提示符中打印编码的亚洲字符(gb2312)?
我在一家公司工作,使用的是Python编程语言的3.1版本,最近遇到了一个问题:如何在命令提示符上打印一些编码的亚洲字符(中文、日文、韩文)呢?
我做了一些研究并尝试了几种方法,但都没有成功:
import sys
import codecs
print(sys.getdefaultencoding()) # prints out UTF-8
fileObj = codecs.open("test.txt", "r", "eucgb2312_cn")
content = fileObj.read()
print(content)
导致这个错误的原因在于最后一行代码:
C:\Documents and Settings\Michael Mao\Desktop>test.py
utf-8
Traceback (most recent call last):
File "C:\Documents and Settings\Michael Mao\Desktop\test.py", line 6, in <module>
print(u)
File "C:\tools\Python31\lib\encodings\cp437.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u5377' in position 3: character maps to < undefined >
我不能把默认编码从UTF-8改成其他的,所以我觉得这可能是导致输出无法正确显示的问题。
有没有人能帮我解决这个问题?非常感谢!
3 个回答
0
如果你自己打开了命令提示符窗口,在运行 test.py 之前,输入以下命令:
mode con cp select=936
如果你的 Python 程序是通过其他方式启动的,你需要让它以正确的代码页打开控制台窗口。
1
我无法将默认编码从UTF-8更改为其他任何编码。
我觉得你的控制台并没有使用UTF-8作为默认编码:
文件 "C:\tools\Python31\lib\encodings\cp437.py"
cp437是旧版DOS终端的编码方式,它确实无法打印中文字符。
可以查看bug 1602,里面有一个批处理文件的技巧,可以让Windows和Python 3在控制台中使用UTF-8(编码页65001),不过一般来说,控制台对于非ASCII字符一直都存在问题,直到有人把Python改成使用WriteConsoleW,而不是标准的C语言输入输出函数,这种情况才会有所改善。
2
我解决了这个问题。当我在编写字典的时候,遇到了这个问题。
#coding=utf-8
import codecs
import sys
# import imp
# imp.reload(sys)
# sys.setdefaultencoding('utf8')
dictFileName = 'abstract.dict'
print(sys.getdefaultencoding())
print(sys.stdout.encoding)
def readDict():
print("start reading dict...")
#dictObject = codecs.open(dictFileName,'rb', encoding = 'utf-8')#, encoding = 'utf-8')
dictObject = open(dictFileName, 'rb')
try:
print('open file success!')
#dictObject.seek(0x1852c)
chunk = dictObject.read(0x5f0) #0x5f0
print(len(chunk))
#chunk = dictObject.read(0x1)
print('read success')
#print(chunk.decode("utf-8"))
#print(chunk.encode('utf-8').decode('gb18030'))
#sys.stdout.buffer.write(chunk.encode('gb18030'))
sys.stdout.buffer.write(chunk.decode('utf-8').encode('gb18030'))
finally:
dictObject.close()
readDict()
input()