French

French - 技术经验
澄其心, 断其欲, 方能悟道
  1. 首页
  2. 编程语言
  3. Python
  4. 正文

Python VTT字幕文件转SRT字幕文件

2023-06-01 2697点热度 0人点赞 0条评论

最近写新功能中,遇到了一个问题呢,视频处理软件只支持SRT格式的字幕文件, 但系统只能生成VTT格式的字幕文件,故此写了此方法进行格式转换,方便视频软件调用

# VTT字幕文件转SRT字幕文件
def vtt_to_srt(vtt_path, save_path):
    """
    @编写作者: French \n
    @创建时间: 2023-06-01 \n
    @修改时间: 2023-06-01 \n
    @功能描述: VTT字幕文件转SRT字幕文件 \n

    Args:
        vtt_path(str): VTT字幕文件路径
        save_path(str): SRT保存文件路径

    Returns:
        None
    """
    # 计数器
    num = 1
    # 读取文件
    vtt_file = open(vtt_path, "r", encoding="utf-8")
    # 读取文件内容
    vtt_file_content = vtt_file.read()
    # 清除文件多余内容
    vtt_file_content = vtt_file_content.split("\n")
    vtt_file_content = [i for i in vtt_file_content if len(i) > 0 and i != "WEBVTT"]
    # 设置时间轴
    time_list = []
    # 设置内容轴
    content_list = []
    # 遍历VTT文件内容
    for i in vtt_file_content:
        # 写入时间轴
        if "-->" in i:
            # 处理时间格式
            i = i.replace(".", ",")
            time_list.append(i)
        # 写入内容轴
        else:
            # 处理内容数据
            i = i.replace(" ", "")
            content_list.append(i)
    # 判断时间轴和内容数据是否对得上
    if len(time_list) == len(content_list):
        print(123)
        with open(save_path, "w", encoding="utf-8") as srt_file:
            for i in range(len(time_list)):
                srt_file.write("{}\n".format(num))
                srt_file.write("{}\n".format(time_list[i]))
                srt_file.write("{}\n".format(content_list[i]))
                srt_file.write("\n")
                num += 1
    else:
        print("VTT字幕文件有误")
    vtt_file.close()

 

本作品采用 知识共享署名-非商业性使用 4.0 国际许可协议 进行许可
标签: 暂无
最后更新:2023-06-01

French

这个人很懒,什么都没留下

打赏 点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2018-2024 French. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蜀ICP备2022008471号-1

川公网安备 51130202000393号