简单介绍:
说明: 此模块主要用来实现字符串/文件编码检测
快速安装:
1 | pip install --upgrade chardet |
常用方法:
1 | chardet.detect(aBuf) -> dict |
说明: 检测字符串编码,返回一个字典包含confidence编码匹配准确率,encoding最终检测的编码,当aBuf为空时可能encoding为None,所以最好判断一下
最佳实践:
1. FirmwareUpload会自动对接OA系统及对应SVN服务器,自动定期读取最新OA发布的固件程序及ReleaseNote,但ReleaseNote中间可能由OA流经不同的部门被修改,无法区别同步下来的编码,由于最终会读取ReleaseNote文件生成对应的目录结构自动发布到UpgradeServer,所以希望可以准确识别编码统一转换为utf-8编码?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2016-11-23 11:14:15 # @Author : 李满满 (xmdevops@vip.qq.com) # @Link : http://xmdevops.blog.51cto.com/ # @Version : $Id$ from __future__ import absolute_import # 说明: 导入公共模块 import os import chardet # 说明: 导入其它模块 if __name__ = = '__main__' : res_lines = [] with open ( 'ChangeLog_Chinese.dat' , 'r+b' ) as fd: res_line = os.linesep for line in fd: line = line.lstrip() encoding = chardet.detect(line).get( 'encoding' , None ) print encoding if encoding: res_line = line.decode(encoding, 'replace' ).encode( 'utf-8' ) res_lines.append(res_line) print res_lines |
登录乐搏学院官网http://www.learnbo.com/
或关注我们的官方微博微信,还有更多惊喜哦~

本文出自 “满满李 - 运维开发之路” 博客,请务必保留此出处http://xmdevops.blog.51cto.com/11144840/1875749