【教程】如何用Python中的chardet去检测字符编码类型

8 篇文章 0 订阅
2 篇文章 0 订阅

【背景】

之前已经使用过chardet了,也算用了不少次了。

之前也写过和chardet相关的:

【已解决】windows下,安装python的chardet

【问题】Python中用Chardet检测出来从Windows的cmd中输入的字符串的编码是KOI8-R,而不是所希望的GBK或GB2312

【整理】Python的字符编码检测库:charade和chardet的区别

但是没写教程,举例说明如何使用。

现在去举例解释解释。

【python示例代码演示如何用chardet检测字符串的编码类型】

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
【教程】如何用Python中的chardet去检测字符编码类型
 
Version:    2013-09-16
Author:     Crifan Li
"""
 
import chardet;
 
def chardet_detect_str_encoding():
     """
         Demo how to use chardet to detect string encoding/charset
     """
     inputStr  = "当前文件时UTF-8,所以你所看到的这段字符串,也是UTF-8编码的" ;
     detectedEncodingDict  = chardet.detect(inputStr);
     print "type(detectedEncodingDict)=" , type (detectedEncodingDict);  #type(detectedEncodingDict)= <type 'dict'>
     print "detectedEncodingDict=" ,detectedEncodingDict;  #detectedEncodingDict= {'confidence': 0.99, 'encoding': 'utf-8'}
     detectedEncoding  = detectedEncodingDict[ 'encoding' ];
     print "That is, we have %d%% confidence to say that the input string encoding is %s" % ( int (detectedEncodingDict[ 'confidence' ] * 100 ), detectedEncoding);
 
if __name__  = = '__main__' :
     chardet_detect_str_encoding();

 

【总结】

相对来说,chardet,算是很好用的了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值