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

版权声明:本文遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明

原文链接:https://blog.csdn.net/ycpriscilla/article/details/132127363

最近遇到需要整体修改时间的字幕文件,于是在网上搜索各种修改字幕时间的软件和手段,最后尝试下来,这些代码最符合我的需求。遂依据版权协议转载,并完善了部分注释

以下是 Python 代码,使用时只需修改 lag 值(第5行)和 zmfile 值(第6行)即可。修改后的文件会自动在文件名末尾加上 _debug 以便区分

ASS 格式

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

lag = 10*1000 # 时间差,单位为毫秒。10*1000即向后延时10秒,向前移动加上负号即可
zmfile = 'C:\\example.ass' # 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 # 时间差,单位为毫秒。10*1000即向后延时10秒,向前移动加上负号即可
zmfile = 'C:\\example.srt' # 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)
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇