批量转换字幕编码的脚本

wen 实用脚本 2

本文目录导读:

批量转换字幕编码的脚本

  1. 安装依赖
  2. 使用方法
  3. 功能特点
  4. 注意事项

这里提供一个批量转换字幕编码的Python脚本,支持多种编码格式互转:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量转换字幕文件编码格式
支持 .srt, .ass, .ssa, .sub 等常见字幕格式
"""
import os
import sys
import argparse
from pathlib import Path
import chardet
# 常见字幕编码格式
ENCODINGS = [
    'utf-8', 'utf-8-sig', 'utf-16', 'utf-16-le', 'utf-16-be',
    'gbk', 'gb2312', 'gb18030',
    'big5', 'big5hkscs',
    'shift_jis', 'euc-jp',
    'euc-kr',
    'latin-1', 'iso-8859-1',
    'cp1252', 'cp1251', 'cp1250'
]
def detect_encoding(file_path, max_bytes=100000):
    """
    检测文件编码
    """
    with open(file_path, 'rb') as f:
        raw_data = f.read(max_bytes)
    result = chardet.detect(raw_data)
    encoding = result['encoding']
    confidence = result['confidence']
    if encoding is None:
        return None, 0
    # 规范化编码名称
    encoding = encoding.lower()
    if encoding in ['ascii', 'ansi']:
        return 'utf-8', confidence
    elif encoding == 'iso-8859-1':
        return 'latin-1', confidence
    return encoding, confidence
def convert_file(file_path, target_encoding='utf-8', source_encoding=None, backup=True):
    """
    转换单个字幕文件编码
    """
    try:
        # 检测原编码
        if source_encoding is None:
            source_encoding, confidence = detect_encoding(file_path)
            if source_encoding is None:
                print(f"⚠ 无法检测编码: {file_path}")
                return False
            print(f"  检测到编码: {source_encoding} (置信度: {confidence:.1%})")
        # 读取文件
        with open(file_path, 'rb') as f:
            raw_data = f.read()
        # 解码
        try:
            text = raw_data.decode(source_encoding)
        except UnicodeDecodeError:
            print(f"✗ 解码失败: {file_path} (编码: {source_encoding})")
            return False
        # 检查是否需要转换
        if source_encoding.lower() == target_encoding.lower():
            print(f"  无需转换: {file_path}")
            return True
        # 备份原文件
        if backup:
            backup_path = file_path.with_suffix(file_path.suffix + '.bak')
            if not backup_path.exists():
                file_path.rename(backup_path)
                print(f"  备份原文件: {backup_path.name}")
        # 写入目标编码
        with open(file_path, 'w', encoding=target_encoding) as f:
            f.write(text)
        print(f"✓ 转换成功: {file_path} -> {target_encoding}")
        return True
    except Exception as e:
        print(f"✗ 转换失败: {file_path}")
        print(f"  错误: {str(e)}")
        return False
def batch_convert(input_path, target_encoding='utf-8', source_encoding=None,
                  recursive=False, backup=True, extensions=None):
    """
    批量转换字幕文件
    """
    if extensions is None:
        extensions = ['.srt', '.ass', '.ssa', '.sub', '.smi', '.idx']
    path = Path(input_path)
    if path.is_file():
        # 单个文件
        if path.suffix.lower() in extensions:
            convert_file(path, target_encoding, source_encoding, backup)
        else:
            print(f"跳过非字幕文件: {path}")
    elif path.is_dir():
        # 目录
        pattern = '**/*' if recursive else '*'
        files = [f for f in path.glob(pattern) if f.is_file() and f.suffix.lower() in extensions]
        if not files:
            print(f"未找到字幕文件 in {path}")
            return
        print(f"找到 {len(files)} 个字幕文件")
        success = 0
        fail = 0
        for f in files:
            if convert_file(f, target_encoding, source_encoding, backup):
                success += 1
            else:
                fail += 1
        print(f"\n完成! 成功: {success}, 失败: {fail}")
    else:
        print(f"路径不存在: {input_path}")
def list_encodings():
    """列出支持的编码格式"""
    print("支持的编码格式:")
    for i, enc in enumerate(ENCODINGS, 1):
        print(f"  {i:2d}. {enc}")
def main():
    parser = argparse.ArgumentParser(
        description='批量转换字幕文件编码格式',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例:
  # 转换单个文件为UTF-8
  python subtitle_encoding_converter.py input.srt
  # 转换目录下所有字幕为UTF-8
  python subtitle_encoding_converter.py ./subtitles/
  # 递归转换目录及其子目录
  python subtitle_encoding_converter.py ./subtitles/ -r
  # 指定源编码转换
  python subtitle_encoding_converter.py input.srt -s gbk
  # 转换到指定目标编码
  python subtitle_encoding_converter.py input.srt -t utf-8
  # 不备份原文件
  python subtitle_encoding_converter.py input.srt -nb
  # 列出支持的编码格式
  python subtitle_encoding_converter.py -l
        """
    )
    parser.add_argument('input', nargs='?', help='输入文件或目录路径')
    parser.add_argument('-t', '--target', default='utf-8',
                       help='目标编码 (默认: utf-8)')
    parser.add_argument('-s', '--source', default=None,
                       help='源编码 (默认: 自动检测)')
    parser.add_argument('-r', '--recursive', action='store_true',
                       help='递归处理子目录')
    parser.add_argument('-nb', '--no-backup', action='store_true',
                       help='不备份原文件')
    parser.add_argument('-l', '--list-encodings', action='store_true',
                       help='列出支持的编码格式')
    args = parser.parse_args()
    if args.list_encodings:
        list_encodings()
        return
    if not args.input:
        parser.print_help()
        return
    batch_convert(
        args.input,
        target_encoding=args.target,
        source_encoding=args.source,
        recursive=args.recursive,
        backup=not args.no_backup
    )
if __name__ == '__main__':
    main()

安装依赖

pip install chardet

使用方法

基本使用

# 转换单个文件为UTF-8
python subtitle_converter.py input.srt
# 转换目录下所有字幕
python subtitle_converter.py ./subtitles/
# 递归处理子目录
python subtitle_converter.py ./subtitles/ -r

指定编码

# 指定源编码(不自动检测)
python subtitle_converter.py input.srt -s gbk
# 指定目标编码
python subtitle_converter.py input.srt -t utf-8

其他选项

# 不备份原文件
python subtitle_converter.py input.srt -nb
# 查看支持的编码
python subtitle_converter.py -l

Windows 用户快捷用法

创建 convert_all.bat:

@echo off
python subtitle_converter.py %1 -r
pause

然后拖放文件夹到该批处理文件即可。

功能特点

  1. 自动编码检测:使用 chardet 自动识别文件编码
  2. 备份原文件:转换前自动备份(生成 .bak 文件)
  3. 批量处理:支持目录批量转换
  4. 递归处理:可处理子目录
  5. 多种字幕格式:支持 .srt, .ass, .ssa, .sub 等
  6. 错误处理:显示转换失败的文件及原因

注意事项

  1. 首次使用建议先备份原始文件
  2. 自动编码检测不是100%准确,如有问题请手动指定源编码
  3. 转换大文件时可能需要较长时间

抱歉,评论功能暂时关闭!