字幕文件vtt转srt

import re  
content = []
srt = []
with open('input.vtt','r') as open_file:
	for lines in open_file:
		lines = lines.replace('WEBVTT','') #删除WEBVTT
         # vtt文件中时间可以是00:00.000
         #srt文件中时间必须是 00:00:00,000
		lines = re.sub("(\d{2}:\d{2}).(\d{3})", lambda m: '00:'+m.group(1) + ',' + m.group(2), lines) 
		if lines.strip():
			content.append(lines)
	
for i,line in enumerate(content):
	if i%2 == 0:
		srt.append('\n')
		srt.append(str(int(i/2+1))) #srt文件中添加行数
		srt.append('\n')
	srt.append(line)

with open('output.srt','w') as w_file:
	w_file.writelines(srt)
posted @ 2024-03-21 21:56  华小电  阅读(16)  评论(0编辑  收藏  举报