srt翻译

from deep_translator import GoogleTranslator
import os

def translate_srt(file_path, source_lang='auto', target_lang='en'):
    translated_lines = []
    translator = GoogleTranslator(source=source_lang, target=target_lang)

    with open(file_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    total_lines = len(lines)
    for i, line in enumerate(lines):
        # 打印当前进度
        print(f'Translating line {i+1}/{total_lines}')

        # 跳过字幕编号和时间戳
        if line.strip().isdigit() or '-->' in line:
            translated_lines.append(line)
        elif line.strip():  # 对非空行进行翻译
            translated_line = translator.translate(line.strip())
            # 如果翻译失败(返回 None),则使用原文
            if translated_line is not None:
                translated_lines.append(translated_line + '\n')
            else:
                translated_lines.append(line)
        else:
            translated_lines.append(line)  # 保持空行的原样

    # 将翻译后的内容写入新文件
    output_file = os.path.splitext(file_path)[0] + '_translated.srt'
    with open(output_file, 'w', encoding='utf-8') as file:
        file.writelines(translated_lines)

    print(f'Translation complete. The translated file is saved as {output_file}')

# 示例用法
translate_srt(r"D:\Downloads\sub\test_srt.srt", source_lang='fr', target_lang='en')

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注