Created
October 10, 2020 14:09
-
-
Save JohanAR/f9e7c40e768ffabdb7d81475188d90d1 to your computer and use it in GitHub Desktop.
Rename all subtitles to match movie
This file contains 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
from collections import namedtuple | |
import os | |
import re | |
FileInfo = namedtuple('FileInfo', ['toname', 'subname']) | |
def doit(): | |
directory = os.fsencode('.') | |
matcher = re.compile('.*[sS](\d+)[eE]([0-9\-]+).*') | |
realsuffix = '.mkv' | |
renamesuffix = '.srt' | |
tab = dict() | |
for fil in os.listdir(directory): | |
filename = os.fsdecode(fil) | |
#print (filename) | |
match = matcher.match(filename) | |
if not match: | |
continue | |
num = (match.group(1), match.group(2)) | |
if num not in tab: | |
tab[num] = FileInfo(None, None) | |
if filename.endswith(realsuffix): | |
realbase = filename[:-len(realsuffix)] | |
#print (num, realbase) | |
if tab[num].toname: | |
raise NameError('{0} already has toname {1}'.format(num, tab[num].toname)) | |
else: | |
tab[num] = FileInfo(realbase + renamesuffix, tab[num].subname) | |
elif filename.endswith(renamesuffix): | |
#print (num, filename) | |
if tab[num].subname: | |
raise NameError('{0} already has subname {1}'.format(num, filename)) | |
else: | |
tab[num] = FileInfo(tab[num].toname, filename) | |
else: | |
print ('Ignoring: {0}'.format(filename)) | |
tonames = set() | |
for num, info in tab.items(): | |
if not info.toname: | |
raise NameError('{0} is missing toname'.format(num)) | |
if not info.subname: | |
raise NameError('{0} is missing subname'.format(num)) | |
if info.toname in tonames: | |
raise NameError('{0} duplicate toname'.format(toname)) | |
tonames.add(info.toname) | |
for num, info in tab.items(): | |
print ('rename "{0}" to "{1}"'.format(info.subname, info.toname)) | |
os.rename(os.fsencode(info.subname), os.fsencode(info.toname)) | |
if __name__ == '__main__': | |
doit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment