ewsd12 发表于 2015-6-1 08:51:18

Python 中有关中文编码解码先关

简单记录几点,以备后忘:

1、python 中的默认编码方式为ascii

1
2
3
In : import sys
In : sys.getdefaultencoding()
Out: 'ascii'





2、设置python 中的默认编码方式

1
2
3
4
5
6
In : import sys
In : reload(sys)
<module 'sys' (built-in)>
In : sys.setdefaultencoding('utf-8')
In : sys.getdefaultencoding()
'utf-8'





3、python 头顶部设置的编码格式 # _*_ coding: utf-8 _*_不会影响默认python 的默认编码格式

1
2
3
4
5
#! /usr/bin/env python
# _*_ coding: utf-8 _*_

import sys
print sys.getdefaultencoding()




执行后的结果为 ascii 编码格式

那么python 头顶部设置的编码格式有什么作用呢?
#1、如果代码中有中文注释,就需要此声明
#2、比较高级的编辑器(比如我的emacs),会根据头部声明,将此作为代码文件的格式
#3、程序会通过头部声明,解码初始化 u"人生苦短",这样的unicode对象,(所以头部声明和代码的存储格式要一致)
以上观点来自于 http://python.jobbole.com/81244/ 此文

那做个测试吧:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#! /usr/bin/env python
# _*_ coding: utf-8 _*_

import sys
print sys.getdefaultencoding()

#reload(sys)
#sys.setdefaultencoding('utf-8')

# 会被编码为unicode
s1 = u"这是一个测试1"

# 会被编码为ascii
s2 = "这是一个测试2"

s1.encode('gbk')
s2.encode('gbk')
print s1
print s2




以上测试结果:

1
2
3
4
5
ascii
Traceback (most recent call last):
File "testunicoding.py", line 21, in <module>
    s2.encode('gbk')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 0: ordinal not in range(128)




主要s2这个字符串的默认编码格式为ascii ,无法先decode 成unicode 。出了问题
将默认编码方式更改为utf-8后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#! /usr/bin/env python
# _*_ coding: utf-8 _*_

import sys
print sys.getdefaultencoding()

reload(sys)
sys.setdefaultencoding('utf-8')

print sys.getdefaultencoding()

# 会被编码为unicode
s1 = u"这是一个测试1"

# 会被编码为ascii
s2 = "这是一个测试2"

s1.encode('gbk')
s2.encode('gbk')
print s1
print s2





执行结果:

1
2
3
4
ascii
utf-8
这是一个测试1
这是一个测试2





python 中若要讲一个gbk 编码 转换成 utf-8 编码 , python 时怎么处理的呢?

1
2
s="测试"
s.decode('gbk').encode('utf-8')




即现将s decode 成unicode 后,在从unicode 进行encode 成 utf-8
页: [1]
查看完整版本: Python 中有关中文编码解码先关