Skip to content

Instantly share code, notes, and snippets.

@jaylinski
Last active February 25, 2022 20:16
Embed
What would you like to do?
Convert WebVTT (*.vtt) to SubRip (*.srt) with Python 2/3
import re
import os
def webvtt_to_srt(webvtt):
srt = ""
counter = 1
for line in webvtt.splitlines():
if line.startswith("WEBVTT"):
continue
if counter == 1 and line == "":
continue
matches = re.match(r"^(?P<fh>\d{2}:)?(?P<fm>\d{2}):(?P<fs>\d{2}).(?P<fms>\d{3})\s-->\s(?P<th>\d{2}:)?(?P<tm>\d{2}):(?P<ts>\d{2}).(?P<tms>\d{3})", line)
if matches:
srt += str(counter) + os.linesep
srt += "{}{}:{},{} --> {}{}:{},{}{}".format(
matches.group('fh') or "00:",
matches.group('fm'),
matches.group('fs'),
matches.group('fms'),
matches.group('th') or "00:",
matches.group('tm'),
matches.group('ts'),
matches.group('tms'),
os.linesep
)
counter += 1
else:
srt += line + os.linesep
return srt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment