自动探测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