使用 DeepSeek 写的 vtt 字幕转 srt 字幕的 python 程序
最近豆包赠送的500万tokens没处花,赶紧疯狂地让deepseek帮忙干活,有时在油管下载的原生字幕是vtt格式的文件,而搬运到b站要求上传的是srt格式的字幕文件,所以就让deepseek给写了一个vtt到srt的转换程序,完美运行 👍
这里记录下过程:
广告
问:
使用python帮我写一个vtt字幕转srt字幕的程序,在程序初始化时判断是否传入 vtt字幕文件的路径,如果没后传入vtt字幕的路径,则提示用户输入并等待输入
答:
好的,我为您编写了一个将 WebVTT 字幕转换为 SRT 格式的 Python 程序。以下是完整的代码和说明:
import re import sys import os def convert_vtt_to_srt(vtt_path): try: with open(vtt_path, 'r', encoding='utf-8') as f: vtt_content = f.read() except FileNotFoundError: print(f"错误:文件 '{vtt_path}' 不存在") return except Exception as e: print(f"读取文件时出错:{str(e)}") return blocks = re.split(r'\n{2,}', vtt_content.strip()) srt_blocks = [] counter = 1 # 修改后的正则表达式,完整捕获时间码(含毫秒) timecode_pattern = re.compile( r'((?:\d{1,2}:)?\d{2}:\d{2}[.,]\d{3})\s*-->\s*((?:\d{1,2}:)?\d{2}:\d{2}[.,]\d{3})' ) for block in blocks: lines = block.split('\n') if lines[0].strip().upper() == 'WEBVTT' or not lines: continue # 尝试匹配时间码(支持多行情况) time_match = None for i, line in enumerate(lines): time_match = timecode_pattern.match(line) if time_match: content_start = i + 1 break if not time_match: continue # 处理时间码格式转换 start = time_match.group(1).replace('.', ',') end = time_match.group(2).replace('.', ',') timecode = f"{start} --> {end}" # 提取有效字幕文本 text_lines = [] for line in lines[content_start:]: line = line.strip() if line and not line.startswith(('NOTE', 'STYLE', 'REGION')): # 移除字幕中的样式标签(如<v.example>) line = re.sub(r'<\/?[\w\.]+>', '', line) text_lines.append(line) if text_lines: srt_block = f"{counter}\n{timecode}\n" + '\n'.join(text_lines) srt_blocks.append(srt_block) counter += 1 srt_content = '\n\n'.join(srt_blocks) base_path = os.path.splitext(vtt_path)[0] output_path = f"{base_path}.srt" try: with open(output_path, 'w', encoding='utf-8') as f: f.write(srt_content) print(f"转换成功!输出文件:{output_path}") except Exception as e: print(f"写入文件时出错:{str(e)}") def main(): vtt_path = sys.argv[1] if len(sys.argv) > 1 else input("请输入VTT文件路径:").strip() if not os.path.exists(vtt_path): print(f"错误:路径 '{vtt_path}' 不存在") return if not vtt_path.lower().endswith('.vtt'): print("错误:文件扩展名应为.vtt") return convert_vtt_to_srt(vtt_path) if __name__ == "__main__": main()
功能说明:
使用方式:
1. 通过命令行参数:
python vtt2srt.py subtitle.vtt2. 通过交互式输入:
python vtt2srt.py 请输入VTT文件路径: /path/to/subtitle.vtt注意事项: