Text files are automatically calculated to generate files in srt subtitle format

According to the txt text file, the file is automatically calculated and generated in roughly srt subtitle format, which is convenient for importing into the video clip to generate dubbing with one click.

  1. Read the text in the specified txt file
  2. Split text into multiple sentences
  3. remove empty sentences
  4. Calculate the duration of each sentence
  5. save the srt file
import os
import re

def to_srt(file_path):
    # 读取指定txt文件中的文本
    with open(file_path, 'r', encoding='utf-8') as f:
        text = f.read()

    # 将文本分成多个句子
    sentences = re.split(r'[。!~?]', text)

    # 去除空句子
    sentences = [s.strip() for s in sentences if s.strip()]

    # 计算每个句子的持续时间
    end_time = 0
    srt = ''
    for i, sentence in enumerate(sentences):
        start_time = end_time + 2
        start_time_str = "{:02d}:{:02d}:{:02d},{}".format(int(start_time // 3600), int((start_time % 3600) // 60), int(start_time % 60), "000")
        duration = len(sentence) * 0.25
        end_time = start_time + duration
        end_time_str = "{:02d}:{:02d}:{:02d},{}".format(int(end_time // 3600), i

Guess you like

Origin blog.csdn.net/u012743772/article/details/131601183