...大约 1 分钟
今天给大家分享一个 srt 转化为 lrc 的程序
import os
from natsort import ns, natsorted
import chardet
#获取编码格式,没有chardet库要安装
def get_code(filepath):
with open(filepath,'rb') as f:
return chardet.detect(f.read())['encoding']
#列表字符串拼接成字符
def list_to_str2(out_list):
stryy = ""
for ll in out_list:
stryy = stryy + str(ll) + "\n"
return stryy
#写入文本到文件
def write_file(filename,str1):
print(f'写入文件')
fo = open(filename, "w+", encoding='utf-8')
fo.write(str1)
fo.close()
#顺序读取
def read_content_order22_blank(filename):
print(f'开头读取文本,顺序')
fk3 = open(filename, "r", encoding=get_code(filename))
grafk = fk3.readlines()
fk3.close()
aaby=[]
#去掉换行符
print(f'开头的去掉换行符')
for ssij in grafk:
ssij = str(ssij).replace("\n", "")
if len(ssij)>0:
aaby.append(ssij)
return aaby
def tran_format(strtime):
strtime=str(strtime).replace(" ","")
t1dplace=str(strtime).find(",")
lasnum=strtime[int(t1dplace)+1:int(t1dplace)+3]
purenum=strtime[0:t1dplace]
timelistaa=purenum.split(":")
if str(timelistaa[0])!="00":
dshu3=str(int(timelistaa[0])*60+int(timelistaa[1]))
else:
dshu3=timelistaa[1]
dshu2=timelistaa[2]
outtime=f"[{dshu3}:{dshu2}.{lasnum}]"
return outtime
def zimu_to_lrc_get_file(dir_path):
files = os.listdir(dir_path)
files = natsorted(files, alg=ns.PATH)
dirname = os.path.dirname(dir_path)
outdir = dirname + "/字幕转lrc/"
if not os.path.exists(f"{outdir}"):
print("输出文件夹不存在,帮你自动创建好了")
print("==================================")
os.mkdir(f"{outdir}")
exte_type = '.srt'
for tt in files:
exte_nam = os.path.splitext(tt)[1]
exte_nam0 = os.path.splitext(tt)[0]
if exte_nam:
if str(exte_type) == str(exte_nam) :
aab = dir_path + '/' + tt
aab2 = dir_path + '/' + str(exte_nam0)+ ".txt"
outaab=outdir+str(exte_nam0)+ ".lrc"
os.rename(aab,aab2)
filelist=read_content_order22_blank(aab2)
wb=""
outlist=[]
for kk in filelist:
if not str(kk).isdigit():
if str(kk).find("-->")!=-1:
timenam=kk.split("-->")
time=tran_format(timenam[0])
wb=wb+time
else:
wb=wb+str(kk)
else:
if len(str(wb))>0:
outlist.append(wb)
wb = ""
if len(str(wb)) > 0:
outlist.append(wb)
wb = ""
stryy=list_to_str2(outlist)
write_file(outaab, stryy)
os.rename(aab2, aab)
if __name__ == '__main__':
#srt字幕所在的文件夹,这里是文件夹转换,方便有多个字幕的时候,都放在这个文件夹,可以批量转换。
dir_path=""
zimu_to_lrc_get_file(dir_path)
pass
使用方式
终端执行python srt2lrc.py
注意要把dir_path=
补充完整
Powered by Waline v2.15.8