python - 如何在命令提示符下打印出编码的亚洲字符 (gb2312)?

标签 python windows python-3.x command-prompt

我现在就职于一家使用 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 更改为其他任何编码,所以我认为这是导致输出无法正确呈现的问题。

谁能帮我解决这个问题?非常感谢!

最佳答案

我已经解决了这个问题。我在编写字典时遇到了这个问题。

#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()

关于python - 如何在命令提示符下打印出编码的亚洲字符 (gb2312)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1787497/

相关文章:

Python urllib urlopen 不工作

python - 如何以字符串形式获取cookie

c++ - 在 Windows 窗体上获取文本的方法(非托管 C++ 项目)

python - 模块未找到错误: No module named 'camelcase'

python - 比较两个 numpy 数组的对象 ID

Python贪心算法

python - 从python中的字符串中提取值

python - 在 Python 中运行交互式命令

用于对 URL 进行排序的 Windows 批处理文件脚本

c - 如何在没有 Visual Studio 的情况下为 Windows 编写内核驱动程序?