Skip to content

Instantly share code, notes, and snippets.

@WKBae
Created July 17, 2017 02:00
Show Gist options
  • Save WKBae/ae45afa63c0e44002fdbac0127325f44 to your computer and use it in GitHub Desktop.
Save WKBae/ae45afa63c0e44002fdbac0127325f44 to your computer and use it in GitHub Desktop.
.srt Subtitle Joiner
import re
duration_re = re.compile(r"^\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3}\n$")
with open('input1.srt', 'r', encoding='utf-8') as one, open('input2.srt', 'r', encoding='utf-8') as two, open('result.srt', 'w', encoding='utf-8') as out:
one_lines = []
line = one.readline()
while line:
while len(line) == 1:
line = one.readline()
idx = line
line = one.readline()
duration = duration_re.match(line)
if not duration:
print("[One] Break at duration:", line)
break
lines = []
line = one.readline()
while line and len(line) > 1:
lines.append(line.strip())
line = one.readline()
one_lines.append((duration.group(0), '\n'.join(lines)))
two_lines = []
line = two.readline()
while line:
while len(line) == 1:
line = two.readline()
idx = line
line = two.readline()
duration = duration_re.match(line)
if not duration:
print("[Two] Break at duration:", line)
break
lines = []
line = two.readline()
while line and len(line) > 1:
lines.append(line.strip())
line = two.readline()
two_lines.append((duration.group(0), '\n'.join(lines)))
lines = one_lines + two_lines
lines.sort(key=lambda item: item[0])
index = 1
for item in lines:
out.write('{}\n'.format(index))
out.write(item[0])
out.write(item[1])
out.write('\n\n')
index += 1
print("Done!")
@WKBae
Copy link
Author

WKBae commented Jul 17, 2017

Quick script for joining two .srt subtitles for a same clip. Sorted by time and indexes are recreated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment