Skip to content

Instantly share code, notes, and snippets.

@orhanveli
Forked from jasalt/namesub.py
Last active October 13, 2018 06:27
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 orhanveli/c9e29a36bfabdfe6c03c9792722d8c44 to your computer and use it in GitHub Desktop.
Save orhanveli/c9e29a36bfabdfe6c03c9792722d8c44 to your computer and use it in GitHub Desktop.
rename subtitle files to match video files in same folder
'''
Rename subtitle files in same folder to match the movie file
(for xbmc-share folder)
Jarkko Saltiola 2013
'''
import os
import re
video_types = ["mkv","avi"]
subtitle_types = ["sub", "srt"]
all_files = os.listdir('.') # List current directory items
episodes = [f for f in all_files if f[-3:] in video_types]
subtitles = [f for f in all_files if f[-3:] in subtitle_types]
unmatched_subtitles = [f for f in subtitles if f[:-4] not in episodes]
# Search matching videos for unmatched subtitles, rename subtitles
for subtitle in unmatched_subtitles:
print 'Finding matches for: "%s"' % subtitle
# Find out subtitle's episode-number
# RE-match E1-2 digits without preceding "Part "
episode_number = re.findall(r"E(?<!Part )\d{1,2}", subtitle)[0]
print ' Episode number is: "%s"' % episode_number
for episode in episodes:
match = re.search("(?<!Part )%s" % episode_number, episode)
if match:
new_filename = episode[:-3] + subtitle[-3:]
print ' !found match: "%s", new filename: "%s"' % (episode,new_filename)
if new_filename not in subtitles:
print ' !Renaming: "%s" -> "%s"' % (subtitle,new_filename)
os.rename(subtitle,new_filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment