Created
August 9, 2024 14:41
-
-
Save mio7690/4ff10d9f5d422d6c68381680410c4119 to your computer and use it in GitHub Desktop.
视频-字幕自动重命名对齐脚本
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
import os | |
def remove_common_prefix_suffix(strings): | |
if not strings: | |
return [] | |
# Find common prefix | |
prefix = os.path.commonprefix(strings) | |
# Find common suffix | |
reversed_strings = [s[::-1] for s in strings] | |
suffix = os.path.commonprefix(reversed_strings)[::-1] | |
# Remove prefix and suffix | |
result = [s[len(prefix):-len(suffix)] if suffix else s[len(prefix):] for s in strings] | |
return result, prefix, suffix | |
def main(): | |
# List all files in the current directory | |
files = os.listdir('.') | |
# Define video and subtitle extensions | |
video_extensions = ('.mkv', '.mp4', '.avi') | |
subtitle_extensions = ('.ass', '.srt', '.sub') | |
# Separate video and subtitle files | |
video_files = [f for f in files if f.endswith(video_extensions)] | |
subtitle_files = [f for f in files if f.endswith(subtitle_extensions)] | |
# Remove common prefix and suffix from video and subtitle filenames | |
trimmed_videos, video_prefix, video_suffix = remove_common_prefix_suffix(video_files) | |
trimmed_subtitles, subtitle_prefix, subtitle_suffix = remove_common_prefix_suffix(subtitle_files) | |
# Create a dictionary to map episode numbers to full video filenames | |
video_dict = {trimmed: full for trimmed, full in zip(trimmed_videos, video_files)} | |
# Rename subtitle files to match video filenames | |
for trimmed_subtitle, subtitle in zip(trimmed_subtitles, subtitle_files): | |
if trimmed_subtitle in video_dict: | |
new_name = video_dict[trimmed_subtitle].replace('.mkv', '.ass') | |
print(f'Renaming {subtitle} to {new_name}') | |
os.rename(subtitle, new_name) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment