Written by
Niels Moseley
on
on
Subtitle file handler in Python
A subtitle file handler in Python:
#!/usr/bin/python3
import os
import re
import shutil
def findVideoFiles(dirname : str):
ep_re = re.compile(r"(S[0-9]{2}E[0-9]{2})")
vidfiles = dict()
# iterate over files in
# that directory
for filename in os.listdir(dirname):
f = os.path.join(dirname, filename)
# checking if it is a file
if not os.path.isfile(f):
continue
#print(filename)
episodeMatch = ep_re.search(filename)
if (episodeMatch == None):
continue
episode = episodeMatch.group(1)
fileWithoutExt = os.path.splitext(filename)[0]
if filename.endswith(".mp4"):
vidfiles[episode] = fileWithoutExt
elif filename.endswith(".mv4"):
vidfiles[episode] = fileWithoutExt
elif filename.endswith(".mkv"):
vidfiles[episode] = fileWithoutExt
return vidfiles
def findBestSubFile(dirname : str):
bestFile = ""
bestSize = 0
for filename in os.listdir(dirname):
filepath = os.path.join(dirname, filename)
fileLower = filename.lower()
if ("english" in fileLower):
fsize = os.path.getsize(filepath)
if (fsize > bestSize):
bestSize = fsize
bestFile = filepath
return bestFile
def findDir(searchdir : str, episode : str):
ep_re = re.compile(r"(S[0-9]{2}E[0-9]{2})")
for filename in os.listdir(searchdir):
f = os.path.join(searchdir, filename)
if (os.path.isdir(f)):
episodeMatch = ep_re.search(filename)
if not (episodeMatch == None):
if (episodeMatch.group(1) == episode):
return f
return None
# find the video files
vids = findVideoFiles(".")
for idx, (episode, vidfile) in enumerate(vids.items()):
subtitleDir = findDir("./Subs", episode)
if not (subtitleDir == None):
subtitleFile = findBestSubFile(subtitleDir)
shutil.copyfile(subtitleFile, "{:s}.srt".format(vidfile))
print("Found {:s} in {:s}".format(episode, subtitleDir))