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(附函数)的更多相关文章

  1. Python输入数据类型判断正确与否的函数大全(非常全)

      对于python输入数据类型判断正确与否的函数大致有三类: (1)type(),它的作用直接可以判断出数据的类型 (2)isinstance(),它可以判断任何一个数据与相应的数据类型是否一致,比 ...

  2. [转] Python 字符编码判断

    转自:http://www.cnblogs.com/dkblog/archive/2011/03/02/1980644.html 法一: isinstance(s, str) 用来判断是否为一般字符串 ...

  3. Python 字符编码判断

    题记 在获取中文字符的时候,如果出现乱码的情况,我们需要了解当前的字符串的编码形式.使用下面两种方法可以判断字符串的编码形式. 法一: isinstance(s, str) 用来判断是否为一般字符串 ...

  4. Python编程-编码、文件处理、函数

    一.字符编码补充知识点 1.文本编辑器存取文件的原理(nodepad++,pycharm,word) 打开编辑器就打开了启动了一个进程,是在内存中的,所以在编辑器编写的内容也都是存放与内存中的,断电后 ...

  5. python 字符编码判断 chardet评测

    之前一直想找到一个模块,针对字符判断是什么字符集编码的库 网上有chardet的blog,发现自己的环境有这个库,于是就做了测试 >>> import chardet >> ...

  6. python 练习 simple_server 判断路径及返回函数

    函数 routers 返回一个 urlpatterns 元组,里面包含了路径名和函数名:在 函数 application 中遍历 urlpatterns 元组,路径存在则返回函数名,不存在则返回 40 ...

  7. python中编码判断

    https://www.cnblogs.com/lc-D-a/p/6074878.html python3 用isinstance()检查unicode编码报错

  8. Python—字符编码转换、函数基本操作

    字符编码转换 函数 #声明文件编码,格式如下: #-*- coding:utf-8 -*- 注意此处只是声明了文件编码格式,python的默认编码还是unicode 字符编码转换: import sy ...

  9. python的编码问题

    本文简单介绍了各种常用的字符编码的特点,并介绍了在python2.x中如何与编码问题作战 :) 请注意本文关于Python的内容仅适用于2.x,3.x中str和unicode有翻天覆地的变化,请查阅其 ...

随机推荐

  1. tweenmax.js 文档

    TweenMax 参考http://bbs.9ria.com/thread-214959-1-1.html TweenMax 可能是很多人都用的,包括我 但 是最近发现大量的运用就总会产生这样或那样的 ...

  2. 【转】javascript打印设置

    页面中的代码:<OBJECT id="WebBrowser1" height="0" width="0"        classid ...

  3. Redis集群部署

    1.1.1redis简介 Redis 是一个开源的使用 ANSI C 语言编写.支持网络.可基于内存亦可持久化的日志 型. Key-Value数据库 1.1.2redis常见使用场景 1.会话缓存(S ...

  4. Spring IOC 依赖注入的两种方式XML和注解

    依赖注入的原理 依赖注入的方式---XML配置 依赖注入的方式---注解的方式 Spring 它的核心就是IOC和AOP.而IOC中实现Bean注入的实现方式之一就是DI(依赖注入). 一 DI的原理 ...

  5. 学习Excel 十大函数

    云课堂视频教程 笔记总结: URL:http://study.163.com/course/courseLearn.htm?courseId=1009026#/learn/video?lessonId ...

  6. reinstall ubuntu

    flickering mouse issue http://askubuntu.com/questions/310341/do-graphics-drivers-for-intel-hd-4600-e ...

  7. PCA and kmeans MATLAB实现

    MATLAB基础知识 l  Imread:  读取图片信息: l  axis:轴缩放:axis([xmin xmax ymin ymax zmin zmax cmin cmax]) 设置 x.y 和  ...

  8. Android开源框架:Universal-Image-Loader解析(二)MemoryCache

  9. hash表C语言实现

    算法参考<算法导论>第11章散列表.采用链地址法解决冲突. #include <stdio.h> #include <stdlib.h> #include < ...

  10. 对于undefined和null,还有处理这一类的数组

    var total=0; var data=new Array(5);//定义了data数组,length为5,但是都是元素都是undefined. for(i=0;i<data.length; ...