代码之家  ›  专栏  ›  技术社区  ›  Michael Mao

如何在命令提示下打印编码的中文字符(GB2312)?

  •  1
  • Michael Mao  · 技术社区  · 15 年前

    我现在在一家使用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 回复  |  直到 12 年前
        1
  •  2
  •   haithink    12 年前

    我已经解决了这个问题。当我编写听写程序时,遇到了这个问题。

    #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()
    
        2
  •  1
  •   bobince    15 年前

    我无法将默认编码从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 io函数。

        3
  •  0
  •   Windows programmer    15 年前

    如果您自己打开命令窗口,请在运行test.py之前键入以下命令: 模式控制CP选择=936

    如果您的python程序以其他方式启动,您必须让它用正确的代码页打开其控制台窗口。