美文网首页
解决 Python 在 Windows 终端下中文乱码问题

解决 Python 在 Windows 终端下中文乱码问题

作者: 羽风之歌 | 来源:发表于2015-04-22 14:56 被阅读3140次

为了解决问题我尝试了很多方法,包括:

+ 换用 cmd 控制台,无效

+ 换用 consoleZ 控制台,无效

+ 使用 u'你好'.encode("UTF8").decode("cp936"),还是无效

+ 据说 Python 3 内部字符串全部都是 unicode 模式,换用 Python 3。继续无效

真是没招了……作为终端开发平台 Windows 真是不合格。最后勉强找到一个办法,自己写了个函数做转换:

```

import platform

import sys

def to_zhcn(msg):

    platform_str = platform.platform().lower()

    os_type = 'Linux'

    os_codepage = sys.getfilesystemencoding()

    if re.match(r'windows', platform_str):

        os_type = 'Win'

    if os_type == "Win":

        return msg.decode('utf8').encode(os_codepage)

return msg


```


使用本函数有几个地方要注意:

1. 要打印的中文字符串不要加上 u'' 前缀了,因为加上也没用反而会混淆概念,你以为是 UTF8 字符但实际上还是 cp936

2. 只有向终端打印的字符才需要用本方法转换,如果程序内部互相传参数就不需要转换了,这个方法终归只是解决终端下

中文字符乱码问题的,不要滥用

实例:

```

# 中文没有编码成 unicode

msg = '你好'

print self.to_zhcn(msg=msg)

```


相关文章

网友评论

      本文标题:解决 Python 在 Windows 终端下中文乱码问题

      本文链接:https://www.haomeiwen.com/subject/kunotttx.html