Python 识别文本编码

>>> import chardet
>>> f = open('songs.txt','r')
>>> result = chardet.detect(f.read())
>>> result
{'confidence': 0.99, 'encoding': 'utf-8'}

一次性读取全部文件,可能会浪费点内存(chardet的探测会在搜集到足够数据之后停止,文件比较大时,就比较浪费)

chardet 按照词频统计

 

def description_of(file, name='stdin'):
    """Return a string describing the probable encoding of a file."""
    u = UniversalDetector()
    for line in file:
        u.feed(line)
    u.close()
    result = u.result
    if result['encoding']:
        return '%s: %s with confidence %s' % (name,
                                              result['encoding'],
                                              result['confidence'])
    else:
        return '%s: no result' % name

逐行读取

探测大量重复数据的时间比不重复数据的时间可能要小点。

官网原理解读:

Some character sequences pop up all the time, while other sequences make no sense. A person fluent in English who opens a newspaper and finds “txzqJv 2!dasd0a QqdKjvz” will instantly recognize that that isn’t English (even though it is composed entirely of English letters). By studying lots of “typical” text, a computer algorithm can simulate this kind of fluency and make an educated guess about a text’s language.

In other words, encoding detection is really language detection, combined with knowledge of which languages tend to use which character encodings.

对于某种文本,某些字符串组合经常出现,其他一些字符组合不会出现,依靠研究每种文本的特殊类型的字符组合 便可以从统计学上识别出文本的编码,另一个角度上来说,识别编码就是识别语言类型。(每种语言都有自己最适合的编码)

 

 

 

 

 

 

 

 

 

 

转载于:https://my.oschina.net/PagodaTree/blog/676882

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值