Last active
August 20, 2018 09:16
-
-
Save travislee89/654271e7d0570b95c2bc592ca71e9c13 to your computer and use it in GitHub Desktop.
将下载的字幕里的语言部分的中文,替换成英文,避免部分盒子/播放器不能自动加载字幕。替换和被替换的字符串,须成对填写到replace里。
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# 用法: | |
# python subtitle_rename.py [字幕所在目录] [要被替换的文件名] [替换之后的文件名] | |
# 备注:[字幕所在目录]:可选。会替换该目录下的所有srt和ass文件,如果为空则为当前目录 | |
# [要被替换的文件名]:可选。如果需要替换文件名,则提供前缀部分文件名 | |
# [替换之后的文件名]:可选,如果添加了 [要被替换的文件名],则为必选。 | |
# 示例:python subtitle_rename.py subs/The.Expanse.S03E01.1080p.WEB.H264-DEFLATE The.Expanse.S03E01.1080p.WEB.H264-DEFLATE Yellowstone.2018.S01E01.Daybreak.1080p.AMZN.WEB-DL.DDP2.0.H.264-NTb | |
# 把 subs/The.Expanse.S03E01.1080p.WEB.H264-DEFLATE 目录的 | |
# The.Expanse.S03E01.1080p.WEB.H264-DEFLATE(.+)(srt|ass) 重命名为 | |
# Yellowstone.2018.S01E01.Daybreak.1080p.AMZN.WEB-DL.DDP2.0.H.264-NTb(替换后的英文名称)$2 | |
# current version: 1.0.3 | |
# change: | |
# 1.0.0: 替换后缀的语言,把中文替换成英文。因为部分设备不支持搜索含有中文后缀的字幕文件 | |
# 1.0.3: 增加替换文件名的功能 | |
from sys import argv | |
from os import path, rename, listdir | |
replace_word = [ | |
'简体中文', 'chs', | |
'繁体中文', 'cht', | |
'間體中文', 'chs', | |
'繁體中文', 'cht', | |
'简体', 'chs', | |
'繁体', 'cht', | |
'間體', 'chs', | |
'繁體', 'cht', | |
'中文', 'chs', | |
'英文', 'eng', | |
'英语', 'eng', | |
'english', 'eng' | |
] | |
# 替换和被替换的字符串,须成对填写到replace_word里 | |
length = int(len(replace_word) / 2) * 2 | |
def sub_rename(filename, abs_path): | |
filename_new = str(filename) | |
for i in range(0, length, 2): | |
filename_new = filename_new.replace(replace_word[i], replace_word[i + 1]) | |
if rename_mode is True and filename_new.startswith(name_org): | |
filename_new = filename_new.replace(name_org, name_new) | |
if filename != filename_new: | |
print('Rename %s to %s.' % (filename, filename_new)) | |
rename(path.join(abs_path, filename), path.join(abs_path, filename_new)) | |
else: | |
print('No need to rename %s.' % filename) | |
def replace_file(abs_path): | |
file_list = listdir(abs_path) | |
for f in file_list: | |
if rename_mode is True: | |
if f.startswith(name_org) and f.endswith(('.srt', '.ass')): | |
sub_rename(f, abs_path) | |
else: | |
pass | |
elif f.endswith(('.srt', '.ass')): | |
sub_rename(f, abs_path) | |
else: | |
pass | |
if __name__ == '__main__': | |
name_org, name_new = '', '' | |
rename_mode = False | |
if len(argv) <= 1: | |
abs_path = path.abspath('.') | |
elif len(argv) >= 4: | |
abs_path = path.abspath(argv[1]) | |
name_org = argv[2] | |
name_new = argv[3] | |
rename_mode = name_org != name_new | |
else: | |
abs_path = path.abspath(argv[1]) | |
replace_file(abs_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment