Skip to content

Instantly share code, notes, and snippets.

@Pastez
Created November 11, 2014 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pastez/e6d9311007d6387edf88 to your computer and use it in GitHub Desktop.
Save Pastez/e6d9311007d6387edf88 to your computer and use it in GitHub Desktop.
Converts TXT (MicroDVD, MPL2) subtitles to SRT (SubRip) format
#!/usr/bin/python
import sys, getopt, math
FORMAT_MICRO_DVD = "}"
FORMAT_MPL2 = "]"
def addZero(ts):
if len(ts) < 2:
ts = '0' + ts
return ts
def secondsToTimeformat(s):
output = '';
h = int(math.floor(s / 3600))
s -= h * 3600
output += addZero(str(h)) + ":"
m = int(math.floor(s / 60))
s -= m * 60
output += addZero(str(m)) + ":"
ss = int(math.floor(s))
s -= ss
output += addZero(str(ss)) + ',' + str(s)[2:5]
return output
def main(argv):
fps = 23.976
if len(argv) == 0:
print "pasTxtSrt.py <input_file> <optional_fps>"
print "default fps is " + str(fps)
return
inputfile = argv[0]
if len(argv) > 1:
fps = float(argv[1])
print 'input file: ' + inputfile
print 'fps: ' + str(fps)
fileContent = open( inputfile, "r" )
format = ''
srtOutput = ''
l = 0;
intro = 1
for line in fileContent:
if len(line) < 7: continue
if len(format) == 0:
if line[0] == '{': format = FORMAT_MICRO_DVD #MicroDVD
elif line[0] == '[': format = FORMAT_MPL2 #MPL2
l += 1
timeBeginSIndex = 1
timeBeginEIndex = line.find(format)
timeEndSIndex = timeBeginEIndex + 2
timeEndEIndex = line.find(format, timeEndSIndex)
text = line[timeEndEIndex+1:]
text = text.replace('|','\n')
frameStart = float(line[timeBeginSIndex:timeBeginEIndex])
frameEnd = float(line[timeEndSIndex:timeEndEIndex])
secondsStart = 0.0
secondsEnd = 0.0
if format == FORMAT_MICRO_DVD:
secondsStart = frameStart / fps
secondsEnd = frameEnd / fps
elif format == FORMAT_MPL2:
secondsStart = frameStart / 10
secondsEnd = frameEnd / 10
text = text.replace('/','<i>',len(text))
if intro == 1:
srtOutput += str(l) + '\n'
srtOutput += "00:00:00,00 --> 00:00:03,00" + '\n'
srtOutput += "TXT TO SRT\nDla Ukochanej Asi\nwww.pastez.com\n\n"
l += 1
intro = 0
srtOutput += str(l) + '\n'
srtOutput += secondsToTimeformat(secondsStart) + " --> " + secondsToTimeformat(secondsEnd) + '\n'
srtOutput += text + '\n'
outputFile = open(inputfile[:-3]+'srt', "w")
outputFile.write(srtOutput)
outputFile.close()
if __name__ == "__main__":
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment