码迷,mamicode.com
首页 > 编程语言 > 详细

Sublime和Python中文编码的一些问题

时间:2014-11-22 23:02:14      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   文件   

Windows下的控制台中,应该是这样的逻辑:

1、如果是Unicode字符串的话,首先根据控制台编码进行转换

2、之后进行输出

所以在Windows控制台下,假设str = u‘中文‘,

1、直接print str是可以正确输出的

2、print str.encode(‘gbk‘)或者print str.encode(‘gb2312‘)是正确输出的

3、print str.encode(‘utf-8‘)是输出乱码

 

在Windows系统下的Sublime Text中,假设str = u‘中文‘,

1、如果直接print str的时候,会提示

‘ascii‘ codec can‘t encode characters in position 0-1: ordinal not in range(128)

这是因为它试图用系统默认编码(Windows下默认是ascii)去对Unicode字符串进行encode,碰到中文肯定是失败的

2、如果print str.encode(‘utf-8‘)是可以在Sublime Text中正确输出的

3、如果pirnt str.encode(‘gbk‘)或者print str.encode(‘gb2312‘),会提示

[Decode error - output not utf-8]

可能是因为Sublime Text只接受utf-8的输出吧

 

总结上述流程,Sublime Text的流程应该是

1、判断字符串是否是Unicode

2、如果是的话,就先对其用系统默认编码来进行encode

3、判断字节串是否是utf-8编码,如果是的话,就输出

 

为了解决Windows下Sublime Text这个问题,可以通过以下两种办法:

1、将以下代码加到程序的头部

import sys
default_encoding = utf-8
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)

网上有说插入到sublime_plugin.py中,但是试验了一下,不行

2、在系统环境变量中添加PYTHONIOENCODING(大小写无所谓),值为utf-8

 

这样子,当想输出中文的时候,直接print str,str是Unicode字符串,这样子无论是在Sublime Text还是控制台中都是正确的结果了!

 

注:

chardet可以用来检测文件编码,还有codecs模块用来做编码相关的一些工作,以下这篇文章可以作为文件编码相关问题的参考

Python字符编码问题,chardet,codecs

参考文章:

PYTHON-进阶-编码处理小结

Sublime和Python中文编码的一些问题

标签:style   blog   http   io   ar   color   os   sp   文件   

原文地址:http://www.cnblogs.com/summerwinter/p/4115806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!