Python脚本调整srt字幕的时间轴

imen发布

前两天刚弄下来一部蓝光版的动画片,今晚忍不住想看了。可是射手上蓝光版的字幕还没出,评价好的只有DVDrip版本。弄下来后发现CD1的时间轴完美匹配,CD2的时间轴需要延迟3000多秒。

本来mplayer提供了”-subdelay”参数来调整字幕延迟的,可惜在MplayerX中一直没成功,”Command + ]”又只适合微调,于是就简单写了个Python脚本来处理。使用方式:python srtdelay.py xxx.srt time。其中xxx.srt是需要调整时间轴的字幕文件,time是需要调整的时间,单位为秒,支持小数。如果时间轴需要往后调,则time为正数,反之则为负数。

详细代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys, re, datetime

def generate(old_timeline, sec, microsec):

hour, minute, second, millisecond = \
map(int, (re.split(r'[:,\.]', old_timeline) ))

new_timeline = datetime.datetime(2012, 5, 13, \
hour, minute, second, millisecond*1000) + \
datetime.timedelta(seconds=sec, microseconds=microsec)

return '%02d:%02d:%02d,%03d' % \
(new_timeline.hour, new_timeline.minute, \
new_timeline.second, new_timeline.microsecond/1000)

try:
old_srt_name = sys.argv[1]
old_srt = open(old_srt_name, "r")
except IOError:
print >> sys.stderr, "Failed to open srt file input\n"

try:
new_srt_name = sys.argv[1] + "_new"
new_srt = open(new_srt_name, "w")
except IOError:
print >> sys.stderr, "Failed to open srt file output\n"

print "Start to process ..."

# get time that user input
delay = (float)(sys.argv[2])

# get seconds want to delay
second = (int)(delay)

# get microseconds want to delay
microsecond = (int)(1000000*(delay - second))

# Timeline like: "00:12:59,123    ->    00:13:00,291"
pattern = re.compile(r"(\d{2}:\d{2}:\d{2}[.,]\d{3}).*(\d{2}:\d{2}:\d{2}[.,]\d{3})")

for line in old_srt:
if re.match(pattern, line):
start, end = re.match(pattern, line).groups()
result_start = generate(start, second, microsecond)
result_end = generate(end, second, microsecond)
line = line.replace(start, result_start).replace(end, result_end)

print '.',

new_srt.write(line)

print
print "Processed successfully!"

old_srt.close()
new_srt.close()
分类: Python

1 条评论

CoovielmToott · 2013年3月4日 13:33

. . .

发表评论

Avatar placeholder
%d 博主赞过: