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
- python 中文编码 问题
- Python 中文编码问题
- Python 中文 编码问题
- python中文编码问题
- python 中文编码问题
- python中文编码问题
- python 中文编码问题
- python中文编码问题
- python中文编码问题
- python中文编码问题
- python中文编码问题
- python中文编码问题
- Python中文编码问题
- python中文编码问题
- Python中文编码问题
- python 中文编码问题
- Python中文编码问题
- Python中文编码问题
- Build Your First Mobile App With Ionic 2 & Angular 2 - Part 2
- OpenCV学习HighGUI
- 【华为OJ】【096-表达式求值】
- java学习笔记5.22多维数组以及对象和类
- 设计模式 装饰者模式 带你重回传奇世界
- python 中文编码问题
- Java基础笔记(截止到面向对象思想)
- C++动态生成二维数组
- 设计模式 观察者模式 以微信公众服务为例
- Build Your First Mobile App With Ionic 2 & Angular 2 - Part 3
- 设计模式 策略模式 以角色游戏为背景
- VirtualKD+Windbg+vmware 极速调试+Windbg下载符号
- bzoj 1212: [HNOI2004]L语言(AC自动机+DP)
- 【华为OJ】【097-24点游戏算法】