python编码转换
来源:互联网 发布:软件游戏猎手 编辑:程序博客网 时间:2024/05/29 08:55
参见:http://www.pythonclub.org/python-basic/codec
主要介绍了python的编码机制,unicode, utf-8, utf-16, GBK, GB2312,ISO-8859-1 等编码之间的转换。
常见的编码转换分为以下几种情况:
1.自动识别字符串编码:
#coding:utf8#chartdet官方下载网站http://pypi.python.org/pypi/chardetimport urllibimport chardetrawdata = urllib.urlopen('http://www.google.cn/').read()print chardet.detect(rawdata)
输出:
#confidence是可信度,encoding是编码{'confidence': 0.99, 'encoding': 'utf-8'}
2.unicode转换为其他编码
#coding:utf8a = u'中文'a_gb2312 = a.encode('gb2312')print a_gb2312
输出:中文
3.其他编码转换为unicode
#coding:utf8a = u'中文'a_gb2312 = a.encode('gb2312')print a_gb2312#a为gb2312编码,要转为unicode. unicode(a, 'gb2312')或a.decode('gb2312')print [unicode(a_gb2312,'gb2312')]print [a_gb2312.decode('gb2312')]
输出:
中文[u'\u4e2d\u6587'][u'\u4e2d\u6587']
4.非unicode编码之间的相互转化
#coding:utf8a = u'中文'a_gb2312 = a.encode('gb2312')print a_gb2312#编码1转换为编码2可以先转为unicode再转为编码2a_unicode = a_gb2312.decode('gb2312')print [a_unicode]a_utf8 = a_unicode.encode('utf8')#dos不识别utf8编码,直接输出会是乱码print [a_utf8]
5.判断字符串编码#coding:utf8#isinstance(s, str) 用来判断是否为一般字符串 #isinstance(s, unicode) 用来判断是否为unicode 3#如果一个字符串已经是unicode了,再执行unicode转换有时会出错(并不都出错) def u(s,encoding): if isinstance(s,unicode): return s else: return unicode(s,encoding)6.汉字转化为unicode编码#coding:utf8#该方法没看懂,先留下了name = '中国' name = name.decode('utf8')print nametmpname = ""for c in name: c = "%%u%04X" % ord(c) tmpname += cprint tmpname输出结果:中国%u4E2D%u56FD
0 0
- python中编码转换
- python 编码转换
- python 编码转换
- python 编码转换
- python 编码转换
- python编码转换
- python编码转换
- PYTHON编码转换小记
- PYTHON编码转换
- Python - 编码转换
- python中文编码转换
- python 编码转换
- python编码转换
- python中的编码转换
- Python 编码转换
- Python - 编码转换
- python 编码转换
- Python - 编码转换
- OpenGL帧缓冲区 转载
- hdu2066
- 国外程序员推荐:每个程序员都应读的书
- 用例图
- hdu 3791 二叉搜索树(二叉树)
- python编码转换
- 第二周作业
- 磁盘管理四之RAID
- OpenGl 笔记--转载
- Windows绘图—六种映射方式
- linux之日志管理
- MIPS流水线
- tcpdump抓包
- python中文注释问题解决