python 中文编码问题

来源:互联网 发布:数据库实验报告总结 编辑:程序博客网 时间:2024/06/05 15:12

相信中文乱码一直是中国程序员苦逼的事,最近本人就被折腾了一下。
首先编码就是将字符使用计算机形式表示,也就是字节或字节串。ASCII采用单字节,最多也就256种可能字符,UTF-8采用多字节,中文占三个字节,GB2312使用两个字节。

在python内部的统一编码是unicode编码。当我们处理不同编码字符串时就需要进行相互间的转换,而unicode就是一个中间码。如UTF-8先转成Unicode(decode)再转成GB2312(encode)。

先生成一个unicode字符串:

>>> a=u'计算机'>>> print(type(a))<type 'unicode'>

可以编码成不同格式:

>>> a.encode("utf8")'\xe8\xae\xa1\xe7\xae\x97\xe6\x9c\xba'>>> a.encode("gb2312")'\xbc\xc6\xcb\xe3\xbb\xfa'>>> a.encode("gb2312").decode("gb2312")u'\u8ba1\u7b97\u673a'>>> print(type(a.encode("gb2312")))<type 'str'>

因为python是解释语言,在实际编程时,还要涉及源文件的编码格式。
在test.py中输入下面的代码,运行:

a="计算机"print(type(a))print(type(a.decode("utf8"))print(type(a.decode("gb2312"))

这时会抱错,因为python默认使用ASCII对源文件编码

[cos@localhost git]$ python test.py  File "test.py", line 1SyntaxError: Non-ASCII character '\xbc' in file test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

这时可以在源文件中加上编码指令,如UTF-8:

# -*- coding:utf8 -*-a="计算机"print(type(a))print(type(a.decode("utf8"))print(type(a.decode("gb2312"))
[cos@localhost git]$ python ./test.py<type 'str'><type 'unicode'>Traceback (most recent call last):  File "./test.py", line 5, in <module>    print(type(a.decode("gb2312")))UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 4-5: illegal multibyte sequence

对于文件的输入输出,可以使用codecs进行解码,下面是对gb2312编码文件的输出,解码之后都是unicode格式

>>> import codecs>>> f=codecs.open('testout.txt',encoding='gb2312')>>> a=f.readline()>>> print(type(a))<type 'unicode'>>>> print(a)  老王负责管理村广播站。
0 0
原创粉丝点击