一、新建一个文本文件,并重命名为main.py,然后把下面代码粘贴进去;
二、在main.py所在的文件夹下新建vtt和srt两个文件夹;
三、把所有.vtt格式文件放到vtt目录下;
四、在main.py文件所在的目录的地址栏里面输入cmd回车后输入:
python main.py
完整代码:
import os
import re
from pathlib import Path
def convert_timestamp(timestamp):
"""Convert WebVTT timestamp to SRT timestamp format"""
# Add hour if not present (00:04.310 -> 00:00:04,310)
if timestamp.count(':') == 1:
timestamp = "00:" + timestamp
# Replace '.' with ',' for milliseconds
return timestamp.replace('.', ',')
def convert_vtt_to_srt(vtt_content):
"""Convert VTT content to SRT format"""
# Split content into lines and remove empty lines
lines = [line.strip() for line in vtt_content.split('\n') if line.strip()]
# Remove WebVTT header
if lines and lines[0].upper().startswith('WEBVTT'):
lines = lines[1:]
srt_lines = []
subtitle_index = 1
timestamp_pattern = r'(\d{2}:\d{2}\.\d{3}) --> (\d{2}:\d{2}\.\d{3})'
i = 0
while i < len(lines):
line = lines[i]
# Look for timestamp line
match = re.match(timestamp_pattern, line)
if match:
# Add subtitle index
srt_lines.append(str(subtitle_index))
subtitle_index += 1
# Convert and add timestamp
start_time = convert_timestamp(match.group(1))
end_time = convert_timestamp(match.group(2))
srt_lines.append(f"{start_time} --> {end_time}")
# Add subtitle text (all lines until next timestamp or end)
i += 1
while i < len(lines):
next_line = lines[i]
if re.match(timestamp_pattern, next_line):
break
srt_lines.append(next_line)
i += 1
# Add blank line between subtitles
srt_lines.append('')
else:
i += 1
return '\n'.join(srt_lines)
def process_vtt_files():
"""Process all VTT files in the vtt directory"""
# Get the current directory
current_dir = Path.cwd()
# Define input and output directories
vtt_dir = current_dir / 'vtt'
srt_dir = current_dir / 'srt'
# Create srt directory if it doesn't exist
srt_dir.mkdir(exist_ok=True)
# Process each .vtt file
for vtt_file in vtt_dir.glob('*.vtt'):
try:
# Read VTT file
with open(vtt_file, 'r', encoding='utf-8') as f:
vtt_content = f.read()
# Convert content
srt_content = convert_vtt_to_srt(vtt_content)
# Create output file path
srt_file = srt_dir / (vtt_file.stem + '.srt')
# Write SRT file
with open(srt_file, 'w', encoding='utf-8') as f:
f.write(srt_content)
print(f"Successfully converted: {vtt_file.name}")
except Exception as e:
print(f"Error converting {vtt_file.name}: {str(e)}")
if __name__ == '__main__':
print("Starting VTT to SRT conversion...")
process_vtt_files()
print("Conversion completed!")
原文链接:https://www.hongjianjiao.com/2025/05/28/vtt2srt/,转载请注明出处。
评论0