Skip to content

Instantly share code, notes, and snippets.

@ironpark
Created January 8, 2023 01:03
Show Gist options
  • Save ironpark/20cf72fd5d4ce33a6e517c5fa2c65589 to your computer and use it in GitHub Desktop.
Save ironpark/20cf72fd5d4ce33a6e517c5fa2c65589 to your computer and use it in GitHub Desktop.
from datetime import datetime, timedelta
srtFormat = '''{0}
{1} --> {2}
{3}
'''
def srt(index, start, end, text):
return srtFormat.format(index, start, end, text)
def txt2srt(filepath):
subtitle_list = []
with open(filepath, 'r') as file:
for line in file.readlines():
timestr = line.split(' ')[0]
time = datetime.strptime(timestr, '%M:%S.%f')
text = line[len(timestr):].strip()
subtitle_list.append({
'time': time,
'text': text
})
with open(filepath + ".srt", 'w') as file:
for idx, x in enumerate(subtitle_list):
srt_index = idx + 1
start = x['time'].strftime("%H:%M:%S.%f")[:-3]
if idx == len(subtitle_list) - 1:
end = (x['time'] + timedelta(minutes=5)).strftime("%H:%M:%S.%f")[:-3]
else:
end = subtitle_list[idx + 1]['time'].strftime("%H:%M:%S.%f")[:-3]
file.write(srt(srt_index, start, end, x['text']) + "\n")
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
txt2srt("./01-welcome.txt")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment