Created
September 26, 2021 13:37
-
-
Save hedihadi/9368db0920a9030cf6e48c073971c55e to your computer and use it in GitHub Desktop.
this python script will fix SRT files that has extra lines in them
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fixSubtitleWithExtraLines(filePath): | |
oldSTR=[] | |
with open(filePath, "r") as f: | |
oldSTR=f.readlines() | |
newSTR=[] | |
for element in oldSTR: | |
'''remove all the line breaks''' | |
if element !="\n" : | |
newSTR.append(element) | |
'''wherever we see an element with "-->" we'll add a linebreak one index above where we found the said element''' | |
for element in newSTR: | |
if "-->" in element: | |
insert_at = newSTR.index(element) - 1 | |
'''fix the index is lower than 1, that means thats the start of the srt text, so we wont add line breaks to it''' | |
if (insert_at <1): | |
continue | |
'''this code is responsible to add the line break one index above the element''' | |
'''see https://stackoverflow.com/questions/14895599/insert-an-element-at-a-specific-index-in-a-list-and-return-the-updated-list''' | |
element = [y for i, x in enumerate(newSTR) for y in (("\n", x) if i == insert_at else (x,))] | |
newSTR=element | |
with open(filePath, "w") as f: | |
'''now change the list to string and write to the file''' | |
f.write(''.join(str(e) for e in newSTR)) | |
'''example''' | |
'''1 | |
00:00:02,378 --> 00:00:03,211 | |
[ footsteps approaching ] | |
2 | |
00:00:03,295 --> 00:00:04,587 | |
Morty, you got to come on. | |
3 | |
00:00:04,672 --> 00:00:06,130 | |
henlo im python script | |
wow morty your python script is working | |
Look, I love you, Morty, but we | |
both know you're not as fast as | |
4 | |
00:00:06,215 --> 00:00:07,048 | |
What's going on? | |
''' | |
fixSubtitleWithExtraLines("a.txt") | |
'''will become''' | |
'''1 | |
00:00:02,378 --> 00:00:03,211 | |
[ footsteps approaching ] | |
2 | |
00:00:03,295 --> 00:00:04,587 | |
Morty, you got to come on. | |
3 | |
00:00:04,672 --> 00:00:06,130 | |
henlo im python script | |
wow morty your python script is working | |
Look, I love you, Morty, but we | |
both know you're not as fast as | |
4 | |
00:00:06,215 --> 00:00:07,048 | |
What's going on? | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment