python的编码判断_unicode_gbk/gb2312_utf8(附函数)
python中, 我们平常使用最多的三种编码为 gbk/gb2312, utf8 , unicode。 而python中并没有一个函数来进行 编码的判断。今天,主要对这三种编码进行讨论,并给出区分这三种编码的函数。
我们知道,
unicode编码是1位 gbk,gb2312是2位 utf-8是3位
所以,若只有一个汉字,我们可以通过 长度来判断:
len(u'啊') == 1 #True
len(u'啊'.encode("gbk")) == 2 #True
len(u'啊'.encdoe("utf-8")) == 3 #True
但是实际中,往往是一句话,包含好多汉字。于是,我们做如下实验:
- 1,u'啊'.encode("gbk")[0].decode("gbk") 将会提示错误 UnicodeDecodeError: 'gbk' codec can't decode byte 0xb0 in position 0: incomplete multibyte sequence
- 2,u'啊'.encode('utf8')[0].decode("utf8") 将会提示错误 UnicodeDecodeError: 'utf8' codec can't decode byte 0xe5 in position 0: unexpected end of data
- 3,u'啊'.encode('gbk')[0].decode('utf8') 将会提示错误 UnicodeDecodeError: 'utf8' codec can't decode byte 0xb0 in position 0: invalid start byte
- 4,u'啊'.encode('utf8')[0].decode('gbk') 将会提示错误 UnicodeDecodeError: 'gbk' codec can't decode byte 0xe5 in position 0: incomplete multibyte sequence
- 5,u'啊'.decode('utf8') 将会提示错误 UnicodeEncodeError: 'ascii' codec can't encode character u'\u554a' in position 0: ordinal not in range(128)
- 6,u'啊'.decode('gbk') 将会提示错误 UnicodeEncodeError: 'ascii' codec can't encode character u'\u554a' in position 0: ordinal not in range(128)
由以上可以看出,提示错误若出现 ascii,则该句编码位 ascii 无疑,从2,3可以看出 .decode("utf8")可以区分出不同的编码: unexpected end of data 表示 该句为 utf8编码, 而 invalid start byte 则表示 该句为gbk编码或者gb2312编码。
综上,可以编写如下函数来进行编码判断:(python27)
#! -*-encoding:utf8 -*-
def whichEncode(text):
text0 = text[0]
try:
text0.decode('utf8')
except Exception, e:
if "unexpected end of data" in str(e):
return "utf8"
elif "invalid start byte" in str(e):
return "gbk_gb2312"
elif "ascii" in str(e):
return "Unicode"
return "utf8"
if __name__ == "__main__":
print(whichEncode(u"啊".encode("gbk")))
print(whichEncode(u"啊".encode("utf8")))
print(whichEncode(u"啊"))
在网上看到另一种方法,感觉也不错,from: https://my.oschina.net/sanpeterguo/blog/209134,,,,from_from:http://my.oschina.net/u/993130/blog/199214
def getCoding(strInput):
'''
获取编码格式
'''
if isinstance(strInput, unicode):
return "unicode"
try:
strInput.decode("utf8")
return 'utf8'
except:
pass
try:
strInput.decode("gbk")
return 'gbk'
except:
pass def tran2UTF8(strInput):
'''
转化为utf8格式
'''
strCodingFmt = getCoding(strInput)
if strCodingFmt == "utf8":
return strInput
elif strCodingFmt == "unicode":
return strInput.encode("utf8")
elif strCodingFmt == "gbk":
return strInput.decode("gbk").encode("utf8") def tran2GBK(strInput):
'''
转化为gbk格式
'''
strCodingFmt = getCoding(strInput)
if strCodingFmt == "gbk":
return strInput
elif strCodingFmt == "unicode":
return strInput.encode("gbk")
elif strCodingFmt == "utf8":
return strInput.decode("utf8").encode("gbk")
python的编码判断_unicode_gbk/gb2312_utf8(附函数)的更多相关文章
- Python输入数据类型判断正确与否的函数大全(非常全)
对于python输入数据类型判断正确与否的函数大致有三类: (1)type(),它的作用直接可以判断出数据的类型 (2)isinstance(),它可以判断任何一个数据与相应的数据类型是否一致,比 ...
- [转] Python 字符编码判断
转自:http://www.cnblogs.com/dkblog/archive/2011/03/02/1980644.html 法一: isinstance(s, str) 用来判断是否为一般字符串 ...
- Python 字符编码判断
题记 在获取中文字符的时候,如果出现乱码的情况,我们需要了解当前的字符串的编码形式.使用下面两种方法可以判断字符串的编码形式. 法一: isinstance(s, str) 用来判断是否为一般字符串 ...
- Python编程-编码、文件处理、函数
一.字符编码补充知识点 1.文本编辑器存取文件的原理(nodepad++,pycharm,word) 打开编辑器就打开了启动了一个进程,是在内存中的,所以在编辑器编写的内容也都是存放与内存中的,断电后 ...
- python 字符编码判断 chardet评测
之前一直想找到一个模块,针对字符判断是什么字符集编码的库 网上有chardet的blog,发现自己的环境有这个库,于是就做了测试 >>> import chardet >> ...
- python 练习 simple_server 判断路径及返回函数
函数 routers 返回一个 urlpatterns 元组,里面包含了路径名和函数名:在 函数 application 中遍历 urlpatterns 元组,路径存在则返回函数名,不存在则返回 40 ...
- python中编码判断
https://www.cnblogs.com/lc-D-a/p/6074878.html python3 用isinstance()检查unicode编码报错
- Python—字符编码转换、函数基本操作
字符编码转换 函数 #声明文件编码,格式如下: #-*- coding:utf-8 -*- 注意此处只是声明了文件编码格式,python的默认编码还是unicode 字符编码转换: import sy ...
- python的编码问题
本文简单介绍了各种常用的字符编码的特点,并介绍了在python2.x中如何与编码问题作战 :) 请注意本文关于Python的内容仅适用于2.x,3.x中str和unicode有翻天覆地的变化,请查阅其 ...
随机推荐
- iOS UIView上添加mp4视频
ViewController.h文件中添加如下代码: #import <MediaPlayer/MediaPlayer.h> @property(nonatomic,retain) MPM ...
- gitt
一,git config core.autocrlf false 二,vi .git/config[remote "origin"] url = https://github.co ...
- YII2 缩略图生成 第三方包修改
"xj/yii2-thumb-action": "^2.0" 原本的上传路径是全路径 根据日期生成的上传文件夹 不适用 比如 : upload\article\ ...
- 转-IE浏览器自动配置代理脚本-Proxy.PAC文件及PAC相关语法
用笔记本上网时,往返家里和单位,因为单位是用的代理上网,家里是直接连接.因此每次都要修改IE的代理设置,虽然是个小事,但是每次都要修改总是有点烦 ,于是参考GOOGLE,写了一个自动配置代理的脚本.这 ...
- Add listitem with javascript 分类: Sharepoint 2015-07-16 20:23 4人阅读 评论(0) 收藏
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', createListItem);//makes sure sp.js is loaded and the ...
- Cheap Hollister Clothing
(link to hollisterco site), Spectacles don't simply take care of the eye area inside sun; Putting th ...
- HTML <label> 标签
定义:<label> 标签为 input 元素定义标注(标记). 用法: label 元素不会向用户呈现任何特殊效果.不过,它为鼠标用户改进了可用性.如果您在 label 元素内点击文本, ...
- MYSQL 处理批量更新数据的一些经验。
首先,我们需要了解下MYSQL CASE EXPRESSION 语法. 手册传送门:http://dev.mysql.com/doc/refman/5.7/en/control-flow-functi ...
- android 代码优化
http://android.tgbus.com/Android/androidnews/200812/172247.shtml http://blog.163.com/jzq_520/blog/st ...
- putty连接报NetWork error:connection refused
首先通过物理终端进入到linux上,手工检查ssh发现没运行 /etc/init.d/sshd status 使用rpm -V 命令可检查到ssh的软件包正常 /rpm -V openssh-serv ...