将所有的字幕文件统一为utf-8格式

一开始是用的他人的代码,但是总会有异常,后来查询编码的知识,一点点的改,自己写了一个代码,倒是没报错转换成功了

import codecs
import shutil
import re
import os
import chardet

def convert_encoding(filename):
    # Backup the origin file.

    # convert file from the source encoding to target encoding
    content2b = codecs.open(filename, 'rb').read()
    source_encoding = chardet.detect(content2b)['encoding']
    if source_encoding != None:
        content = content2b.decode(encoding = source_encoding, errors = 'ignore')
        if source_encoding != 'utf-8':
            print(source_encoding, filename)
            codecs.open(filename, 'w', encoding='utf-8').write(content)
for root, dirs, files in os.walk('f:/zip/zip/'):
    for file in files:
        filename = os.path.join(root, file)
        convert_encoding(filename)

1.    

content2b = codecs.open(filename, 'rb').read()

content2b获得字幕文件的二进制值

2.

content = content2b.decode(encoding = source_encoding, errors = 'ignore')
content是将contend2b解码文字符形式,解码格式就是原来字幕文件的编码格式,之所以这么麻烦是因为我发现如果直接用codecs.open()读文件,会出现解码报错,而我在程序中解码,就可以用errors = 'ignore'属性来避免,虽然不知道原理,但是能实用就好了,也不打算深究。后面我们在用'utf-8'编码,就需要这个content变量了

3.

codecs.open(filename, 'w', encoding='utf-8').write(content)
用'utf-8'格式重新编码写入文件
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值