用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)

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值