自动探测gbk编码文件并转为utf8
来源:互联网 发布:sql字段追加内容 编辑:程序博客网 时间:2024/06/08 15:07
自动探测gbk编码文件并转为utf8
有时候要将一些部分在windows上的代码在linux上打开,但是因为windows上的默认都是gbk,linux上打开都是乱码。
因为只有部分文件是gbk编码的,所以不能粗暴的全部转换,要先对文件编码进行推测,然后才能决定是否要转换。
以下python
代码实现遍历目录下指定类型文件并自动探测编码,然后将推测出gbk、gb2312的文件转为utf8。
import codecsdef ReadFile (filePath,encoding): with codecs.open(filePath,"r",encoding) as file: try: content = file.read(); return content except UnicodeDecodeError : return ''def WriteFile(filePath,content,encoding): with codecs.open(filePath,"w",encoding) as file: file.write(content)import chardetdef getEncode(filename): with open(filename) as file: result = chardet.detect(file.read()) if result['confidence']>0.9: return result['encoding'] else: print result return ''import osimport os.pathrootdir = os.path.curdirencoding = ['GBK','GB2312']for parent,dirnames,filenames in os.walk(rootdir): for filename in filenames: if filename.endswith('.h') or filename.endswith('.cpp'): file = os.path.join(parent,filename) encode = getEncode(file) if encode in encoding: content = ReadFile(file,encode) if content!='': print 'transform ' +filename+ ' from '+ encode+ ' to utf-8' WriteFile(file,content,'utf8') else: if encode =='': encode = 'unknow' if encode !='utf-8' and encode !='ascii': print 'suspicious file' + file + ' by '+encode
代码中使用chardet库来探测文件编码,这个库非自带的系统库。需要自己下载。
0 0
- 自动探测gbk编码文件并转为utf8
- 批量把文件编码由GBK转为UTF8
- Python文件编码---gbk?OR utf8?
- gbk转为utf8乱码分析
- java自动探测文件的字符编码
- Java自动探测文件的字符编码
- JAVA编码--Gbk-->Utf8
- GBK UTF8 编码转换
- 编码:utf8, unicode, GBK
- 检测某个txt文件是gbk编码还是utf8编码
- Linux批量转换gbk编码文件到utf8编码
- 字符串编码转为UTF8
- php判断是否为GBK编码并转换为utf8
- MFC---GBK文件与UTF8文件编码互转
- Mac下GBK与UTF8编码文件的批量转换
- Mac下GBK与UTF8编码文件的批量转换
- 将代码源文件由utf8转为GBK
- java中字符串 utf8 转为 gbk
- Unity开发原则
- Node——异步编程
- ExecutorService线程池管理
- Intellij IDEA 中的Facets和Artifacts的区别
- 图片的异步加载和双缓存学习笔记——HomeActivity
- 自动探测gbk编码文件并转为utf8
- 图片的异步加载和双缓存学习笔记——DisplayImageOptions
- Const 在C C++里有什么不同
- java问题锦集(持续添加中)
- 图片的异步加载和双缓存学习笔记——ImageLoaderConfiguration
- 图片的异步加载和双缓存学习笔记——ImageLoader
- 开张语
- ActionBarSherlock学习笔记——初始化控件
- ActionBarSherlock学习笔记——添加组件Menu