现在不想说什么编码原理,这篇文章我会把我在python2.7中所遇到的所有编码问题的解决方案都列出来。如果你们真的遇上了python中文编码这个恼人的问题,你把这些方案都试一下,总会有一个可以解决你的问题的。
废话不多说,上栗子:
1.0 程序代码开头加上
import sys
reload(sys)
sys.setdefaultencoding('utf8')
或
import sys
reload(sys)
sys.setdefaultencoding('gbk')
2.0 使用chardet进行编码识别后在编码
#chardet 是python的第三方库,需要下载和安装,pip install chardet
#或者去https://github.com/chardet/chardet这里下载
#下面是我敲的一个编码函数
import chardet
def to_unicode(s):
t=chardet.detect(s)['encoding']
if t:
s=s.decode(t).encode("utf-8")
else:
s=s.decode('gbk').encode("utf-8")
return s
#调用
s=to_unicode("python2.7编码很要命的嘞!")
3.0 使用python字符的编码函数
s="python2.7编码很要命的嘞!"
s=unicode(s)
s=str(s)
4.0 unicode(s,'gbk')
5.0 如果可以的话,用python3吧,这里的编码基本没问题!
总结:
这几种方法,是我很长时间的总结才得来,如果这里真的还解决不了你的问题再看一下这里:
https://blog.csdn.net/u010223750/article/details/56684096
#========================================
网友评论