Skip to content

Instantly share code, notes, and snippets.

@ftabashir
Last active December 13, 2017 06:13
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 ftabashir/9a7eb181c9e5ef973209ede34cc395bc to your computer and use it in GitHub Desktop.
Save ftabashir/9a7eb181c9e5ef973209ede34cc395bc to your computer and use it in GitHub Desktop.
ModifyFarsiEnglishSubtitleDirection: when we type rtl and ltr text in the same file in envirements which doesn't support rtl, it scrambles text. this python script tries to fix it.
import sys
def subModify(subtitleStr):
modified = []
words = subtitleStr.split()
insertIndex = -1
curIsEn = False
preIsEn = False
for word in words:
preIsEn = curIsEn
curIsEn = False
for char in word:
if ord(char)>=ord('A') and ord(char)<=ord('z'):
curIsEn = True
break
if curIsEn != preIsEn:
insertIndex = 0
else:
insertIndex += 1
modified.insert(insertIndex, word)
return " ".join(modified)
def readAndSubModify(inputFile):
modifiedLines = []
with open(inputFile, encoding="utf8") as subtitle_file:
skip = False
for line in subtitle_file:
if skip:
modifiedLines.append(line)
skip = False
elif len(line)==0:
skip = True
modifiedLines.append(line)
else:
modifiedLines.append(subModify(line))
return "\n".join(modifiedLines)
if len(sys.argv)==2:
subFile = sys.argv[1]
modified = readAndSubModify(subFile)
with open("__"+subFile,'w', encoding="utf8") as modFile:
modFile.write(modified)
print("done!")
else:
print("error! try this: python sub.py path-to-subtitle.srt")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment