python转srt格式到vtt格式
1、srt转到vtt格式的原理:1. 在文件头部加上【WEBVTT】关键字;2. 把原文件中记录时间行中的【,】号替换为【.】。其实原理就是这么简单。有些读者会问,直接用文本替换就行了呀,为什么还要写程序来转呢?因为在替换【,】号时,你的字幕文字内容里也有可能存在【,】号。如果一起替换则会把多余的符号一起替换掉。

3、转换格式核心代码:还记得上面代码中调用的convert_srt_to_vtt(file_path, file_name)函数吧。这个就是把srt文件转换为vtt文件的关键,代码及解释如下:def convert_srt_to_vtt(file_path, file_name): prefix_file_name = file_name[:-4] # 获取不带后缀的文件名(如新建vtt文件作准备) with open(os.path.join(file_path, file_name), encoding="utf-8") as inputFile: #打开原srt文件 with open(os.path.join(file_path, prefix_file_name + ".vtt"), mode="w", encoding="utf-8") as outputFile: 打开或新建vtt文件 line_content = "WEBVTT\r\n\r\n\r\n" # vtt格式文件头 outputFile.write(line_content) # 写入到vtt格式文件 for line in inputFile: # 遍历原srt文件的每一行 if "-->" in line: # 判断是否是时间行,这里可以根据自己采取不同方式 line_content = line.replace(",", ".") # 把,替换为. else: line_content = line # 不是时间行就原样输出 outputFile.write(line_content) # 写入到vtt格式文件

5、程序的运行结果:每一个srt文件在转换时都会在命令行输出相应的提示信息:1_chn.srt is converting...convert completely!1_eng.srt is converting...convert completely!1_jpn.srt is converting...convert completely!看到相应文件的【convert completely!】出现后,就可以在原srt文件所在的文件夹内,找到同名的vtt文件。注意,如果本身已存在名同的vtt文件,那么该文件的内容将会被覆盖。

7、完整的vtt2srt.py代码:为了方便大家直接通过复制就能使用,现把完整代码贴到下面,希望能对各位读者有所帮助:import osimport sysdef conv髫潋啜缅ert_srt_to_vtt(file_path, file_name): prefix_file_name = file_name[:-4] with open(os.path.join(file_path, file_name), encoding="utf-8") as inputFile: with open(os.path.join(file_path, prefix_file_name + ".vtt"), mode="w", encoding="utf-8") as outputFile: line_content = "WEBVTT\r\n\r\n\r\n" outputFile.write(line_content) for line in inputFile: if "-->" in line: line_content = line.replace(",", ".") else: line_content = line outputFile.write(line_content)if __name__ == '__main__': args = sys.argv try: if os.path.isdir(args[1]): for file_name in os.listdir(args[1]): if file_name.endswith(".srt"): print(file_name + " is converting...") convert_srt_to_vtt(args[1], file_name) print("convert completely!") elif os.path.isfile(args[1]): (file_path, file_name) = os.path.split(args[1]) if file_name.endswith(".srt"): print(file_name + " is converting...") convert_srt_to_vtt(file_path, file_name) print("convert completely!") else: print("only srt file can converted.") else: raise except: print("arg[1] should be file name or dir.")
