需要一个第一行时间戳,第二行为字幕的TXT文件或doc文件,比如下面的格式
01:01:01
第一行你好
01:02:03
第二行你好
输出后
1
01:01:01,000000 --> 01:01:01,600
<font=#B87333>{\fn宋体\fs20}第一行你好
2
01:02:03,000000 --> 01:02:03,600
<font=#B87333>{\fn宋体\fs20}第二行你好
将输出的rst文件名字改为《电影/视频名称》.srt,和电影放在同一个文件夹打开
代码: 修改于https://blog.csdn.net/weixin_40833881/article/details/122184447
import datetime
import docx
def srt_format(timedelta, line_number=1, start_time=datetime.datetime.strptime('00:00:00,0', '%H:%M:%S,%f'),
font_clor="#B87333", font_size=20, font_name="宋体"):
"""
:param timedelta: 时间间隔,单位 毫秒
:param line_number: 字幕序列号
:param start_time: 字幕起始时间
:param font_clor: 字幕字体颜色
:param font_size: 字幕字体大小
:param font_name: 字幕字体类别
:return: 字幕格式
"""
line = ''
line += str(line_number) + '\n'
end_time = start_time + datetime.timedelta(milliseconds=timedelta)
str_start_time = datetime.datetime.strftime(start_time, '%H:%M:%S,%f')
str_end_time = datetime.datetime.strftime(end_time, '%H:%M:%S,%f')[:-3]
line += str_start_time + " --> " + str_end_time + "\n"
line += "<font=" + font_clor + ">"
line += "{\\fn" + font_name + "\\fs" + str(font_size) + "}"
return line
def txt2rst(read_path='read.txt', write_path='write.rst'):
with open(read_path, 'r', encoding='UTF-8') as read_txt, \
open(write_path, 'w', encoding='UTF-8-sig') as write_file:
line = read_txt.readline()
n_line = 1
while line:
if n_line % 2: # 字幕本体
line = str.split(line, '\n')[0]
line = datetime.datetime.strptime(line, '%H:%M:%S')
line = srt_format(3600, n_line, line)
print(line)
else: # 时间戳
print(line)
write_file.write(line)
line = read_txt.readline()
n_line += 1
txt2rst('输入文件.txt', '输出文件.rst')