创建
创建一个py文件,例如:
convert_lrc_to_srt.py
实现
py代码如下
import os
import re
def lrc_to_srt(lrc_file_path):
# 获取文件名和扩展名
file_name, _ = os.path.splitext(lrc_file_path)
srt_file_path = file_name + '.srt'
with open(lrc_file_path, 'r', encoding='utf-8') as lrc_file, open(srt_file_path, 'w', encoding='utf-8') as srt_file:
index = 1
previous_timestamp = None
for line in lrc_file:
# 匹配 LRC 格式的时间戳
match = re.match(r'\[(\d{2}):(\d{2}\.\d{2})\](.*)', line)
if match:
minutes, seconds, lyric = match.groups()
current_timestamp = f"{int(minutes):02}:{float(seconds):06.3f}".replace('.', ',')
if previous_timestamp is not None:
# 写入上一条字幕
srt_file.write(f"{index}\n")
srt_file.write(f"{previous_timestamp} --> {current_timestamp}\n")
srt_file.write(f"{previous_lyric.strip()}\n\n")
index += 1
previous_timestamp = current_timestamp
previous_lyric = lyric.strip()
# 写入最后一条字幕
if previous_timestamp is not None and previous_lyric:
srt_file.write(f"{index}\n")
srt_file.write(f"{previous_timestamp} --> {current_timestamp}\n")
srt_file.write(f"{previous_lyric.strip()}\n")
print(f"已将 '{lrc_file_path}' 转换为 '{srt_file_path}'")
# 获取当前文件夹内的所有 .lrc 文件并转换
current_directory = os.path.dirname(os.path.abspath(__file__))
for file in os.listdir(current_directory):
if file.endswith('.lrc'):
lrc_to_srt(os.path.join(current_directory, file))
使用
然后命令行输入:
注意:需将需要转化的文件和py放同一个文件夹
python convert_lrc_to_srt.py