Skip to content

Instantly share code, notes, and snippets.

@jslvtr
Created January 14, 2016 00:10
Show Gist options
  • Save jslvtr/bdd3f1209bb410f05b52 to your computer and use it in GitHub Desktop.
Save jslvtr/bdd3f1209bb410f05b52 to your computer and use it in GitHub Desktop.
A small program to convert newline-separated lines into .SRT-compliant files
import datetime
import os
import sys
__author__ = 'Jose Salvatierra'
path = os.path.dirname(os.path.realpath(__file__))
def write_section(content, current_id, last_end_time):
"""
Method to output a string like below:
```
1
00:00:00,000 --> 00:00:04,000
Hi, and welcome to your very first section in this course!
```
"""
output = "\n{}\n".format(current_id)
out = print_time(last_end_time)
output += out
output += content
return output
def increment_variables(current_id, last_end_time):
current_id += 1
current_time = last_end_time + datetime.timedelta(seconds=3)
return current_id, current_time
def print_time(last_end_time, duration=datetime.timedelta(seconds=3)):
"""
Method to output a string like below:
```
00:00:00,000 --> 00:00:04,000
```
"""
start = format_td(last_end_time)
if len(start) < len("0:00:00,000"):
start = "{},000".format(start)
end = last_end_time + duration
output = str(start).replace(".", ",")
output += " --> "
output += "{},000".format(format_td(end))
output += "\n"
return output
def format_td(delta):
s = delta.total_seconds()
hours, remainder = divmod(s, 3600)
minutes, seconds = divmod(remainder, 60)
return '{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds))
def write_to_file(output_file, section):
output_file.write(section)
def get_input(content, output_file, current_id, last_end_time):
section = write_section(content, current_id, last_end_time)
if section != "":
print(section)
write_to_file(output_file, section)
return section
def run(f_path=None):
if f_path is None:
f_path = path
file_read = raw_input("Enter file to read: ")
with open(os.path.join(f_path, file_read), 'r') as fr:
lines = fr.readlines()
file_name = raw_input("Enter the file to save as: ")
current_id = 1
last_end_time = datetime.timedelta(hours=0, minutes=0, seconds=0, microseconds=0)
with open(os.path.join(f_path, file_name), 'a+') as fp:
if lines[0] != "\n":
raise Exception()
get_input(lines[1], fp, current_id, last_end_time)
for i in range(2, len(lines)):
if lines[i] == "\n" and i != len(lines)-1 and lines[i+1] != "\n":
current_id, last_end_time = increment_variables(current_id, last_end_time)
get_input(lines[i+1], fp, current_id, last_end_time)
if __name__ == '__main__':
if len(sys.argv) > 1:
run(sys.argv[1])
else:
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment