用python修改ASS/SRT字幕文件时间

经常遇到,下载的字幕与视频时间对不,要手动微调,很麻烦,所以写个小程序来修改文件,使用时只需要修改lag值就行了。

ASS格式

# 修改字幕时间,ASS格式
import os
import datetime

lag = 10*1000 # 时间差,毫秒
zmfile = 'F:\\电影\\[zmk.pw]美味.Yummy.2019.PROPER.1080p.WEBRip.x265-RARBG.Chs&Eng.中英双语特效字幕\\Yummy.2019.PROPER.1080p.WEBRip.x265-RARBG.Chs&Eng.ass'

(filePath, ext) = os.path.splitext(zmfile)
debugFile = filePath + '_debug'+ext

text = ''

def getRightTime(xtime, lag):
    theTime = datetime.datetime.strptime(xtime, "%H:%M:%S.%f")
    return (theTime + datetime.timedelta(milliseconds=lag)).strftime("%H:%M:%S.%f")[:-4]


with open(zmfile, 'r', encoding='UTF-8') as f:
    for line in f.readlines():
        # print(line, end='')
        if line.startswith('Dialogue'):
            strline = line
            zmlist = line.split(',')
            starttime = zmlist[1]
            endtime = zmlist[2]
            rightStart = getRightTime(starttime, lag)
            rightEnd = getRightTime(endtime, lag)
            strline = strline.replace(starttime, rightStart)
            strline = strline.replace(endtime, rightEnd)
            text = text + strline
            # print(strline, end='')
        else:
            # print(line, end='')
            text = text + line


with open(debugFile, 'w', encoding='UTF-8') as f:
    f.write(text)

SRT模式

# 修改字幕时间,SRT格式
import os
import datetime

lag = 10*1000 # 时间差,毫秒
zmfile = 'F:\\Strip.Club.Massacre.2017.1080p.WEBRip.x265-RARBG\\Subs\\2_English.srt'

(filePath, ext) = os.path.splitext(zmfile)
debugFile = filePath + '_debug'+ext

text = ''


def getRightTime(xtime, lag):
    theTime = datetime.datetime.strptime(xtime, "%H:%M:%S,%f")
    return (theTime + datetime.timedelta(milliseconds=lag)).strftime("%H:%M:%S,%f")[:-3]


with open(zmfile, 'r', encoding='UTF-8') as f:
    for line in f.readlines():
        # print(line, end='')
        if '-->' in line:
            zmlist = line.split('-->')
            starttime = zmlist[0]
            endtime = zmlist[1]
            rightStart = getRightTime(starttime.strip(' '), lag) + ' '
            rightEnd = ' ' + getRightTime(endtime.strip(' ').rstrip('\n'), lag)+'\n'
            line = line.replace(starttime, rightStart)
            line = line.replace(endtime, rightEnd)
            text = text + line
            # print(line, end='')
        else:
            # print(line, end='')
            text = text + line


with open(debugFile, 'w', encoding='UTF-8') as f:
    f.write(text)

你可能感兴趣的:(python)