You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MoviePy处理含繁体中文SRT字幕时UnicodeDecodeError问题求解

解决MoviePy加载繁体中文SRT的UnicodeDecodeError问题

问题

使用MoviePy的SubtitlesClip加载包含繁体中文的SRT字幕文件时触发UnicodeDecodeError,但纯英文内容的SRT可正常处理。

报错原因

Windows环境下Python默认用cp950编码读取文件,而你的繁体中文SRT实际是UTF-8编码,编码不匹配导致解码失败。MoviePy内置的file_to_subtitles函数打开文件时未指定编码,采用系统默认编码,无法正确解析UTF-8格式的繁体中文内容。

解决方案

手动读取SRT文件并指定UTF-8编码,解析成MoviePy要求的字幕格式后传入SubtitlesClip。修改后的代码如下:

import os
from moviepy.video.tools.subtitles import SubtitlesClip
from moviepy.editor import TextClip

# 自定义SRT解析函数,指定UTF-8编码读取
def custom_file_to_subtitles(srt_file):
    subtitles = []
    with open(srt_file, 'r', encoding='utf-8') as f:
        lines = [line.strip() for line in f if line.strip()]
        index = 0
        while index < len(lines):
            # 跳过字幕序号
            index += 1
            # 解析时间轴
            start, end = lines[index].split(' --> ')
            index += 1
            # 收集字幕内容(支持多行)
            text_lines = []
            while index < len(lines) and not lines[index].isdigit() and '-->' not in lines[index]:
                text_lines.append(lines[index])
                index += 1
            subtitles.append(((start, end), '\n'.join(text_lines)))
    return subtitles

# 路径设置
srt_path = "./test.srt"
# 解析字幕内容
parsed_subtitles = custom_file_to_subtitles(srt_path)
# 创建字幕剪辑
subtitle_generator = lambda txt: TextClip(
    txt, 
    font='./TaipeiSansTCBeta-Bold.ttf', 
    fontsize=20, 
    color='white'
)
sub = SubtitlesClip(parsed_subtitles, subtitle_generator).set_position((250,250))

验证说明

替换原代码后重新运行,即可正常加载含繁体中文的SRT文件,字幕能正确渲染到视频中。

内容的提问来源于stack exchange,提问作者hukuto7750

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 16:25:02