【python脚本】lrc歌词文件转换为srt字幕文件

创建

创建一个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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值