Python 识别文本编码
2016-05-17 00:00
316 查看
摘要: python chardet 识别文本编码的原理
一次性读取全部文件,可能会浪费点内存(chardet的探测会在搜集到足够数据之后停止,文件比较大时,就比较浪费)
chardet 按照词频统计
逐行读取
探测大量重复数据的时间比不重复数据的时间可能要小点。
官网原理解读:
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.
对于某种文本,某些字符串组合经常出现,其他一些字符组合不会出现,依靠研究每种文本的特殊类型的字符组合 便可以从统计学上识别出文本的编码,另一个角度上来说,识别编码就是识别语言类型。(每种语言都有自己最适合的编码)
[code=plain]>>> import chardet >>> f = open('songs.txt','r') >>> result = chardet.detect(f.read()) >>> result {'confidence': 0.99, 'encoding': 'utf-8'}
一次性读取全部文件,可能会浪费点内存(chardet的探测会在搜集到足够数据之后停止,文件比较大时,就比较浪费)
chardet 按照词频统计
[code=plain]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.
对于某种文本,某些字符串组合经常出现,其他一些字符组合不会出现,依靠研究每种文本的特殊类型的字符组合 便可以从统计学上识别出文本的编码,另一个角度上来说,识别编码就是识别语言类型。(每种语言都有自己最适合的编码)
相关文章推荐
- Python 3 正则表达式对中文的匹配
- pythonchallenge 解谜 Level 1
- 文成小盆友python-num2 数据类型、列表、字典
- python数据分析之numpy初始化(一)
- python 中的map(), reduce(), filter
- python学习-day2
- python处理大数据
- Ubuntu下用pyenv进行python环境隔离
- 基于Python的朴素贝叶斯算法实现
- 动态内容爬虫
- python Image模块学习
- Python3写简单爬虫
- Python-----格式化字符
- leetcode(10),Roman to Integer(python)
- Python 格式化字符串
- Python点滴(五)-pandas进阶
- Windows下Eclipse+PyDev安装Python开发环境
- python中模拟进行ssh命令的执行
- python中模拟进行ssh命令的执行
- python