将所有的字幕文件统一为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'格式重新编码写入文件

猜你喜欢

转载自blog.csdn.net/qq_25974431/article/details/80214731
今日推荐