自动探测gbk编码文件并转为utf8

本文介绍了一种使用Python脚本自动探测并转换GBK编码文件为UTF-8的方法。通过遍历指定类型的文件,利用chardet库探测文件编码,并针对识别为GBK或GB2312的文件进行编码转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自动探测gbk编码文件并转为utf8

有时候要将一些部分在windows上的代码在linux上打开,但是因为windows上的默认都是gbk,linux上打开都是乱码。
因为只有部分文件是gbk编码的,所以不能粗暴的全部转换,要先对文件编码进行推测,然后才能决定是否要转换。
以下python代码实现遍历目录下指定类型文件并自动探测编码,然后将推测出gbk、gb2312的文件转为utf8。


import codecs

def 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 chardet

def 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 os
import os.path

rootdir = os.path.curdir
encoding = ['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库来探测文件编码,这个库非自带的系统库。需要自己下载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值