使用python将歌词文件(.lrc文件)转换成字典及遍历获取文件夹内所有lrc文件并以lrc格式显示出来

2022-08-09,,,,

import os
class Get_lrcs(): 

    #将lrc文件转换成字典
    def lrc_to_dict(file_path:str,filenmae:str): #需要传入的参数:文件路径,文件名
        with open(file_path+filenmae,encoding='utf8') as f:
            line=f.readlines() #按行读取
            dts="" #拼接字符串
            for i in range(1,len(line)):  #range起始值为1是为了只读取歌词文件
                kk=line[i]='"'+line[i].strip()+'",'
                dt=(kk[0:11]+'":"'+kk[11:])
                dts+=dt+"\n"
                dts1="{"+dts+"}"
            # print(dts1)
            to_dt=eval(dts1) #用eval()将上面的拼接的字符串转换为字典
        return to_dt

    #遍历获取文件夹内的lrc文件名
    def get_lrc_name(file_path:str): #需要传入文件夹路径参数
        dicts=[] #用于存放lrc字典
        for files in os.listdir(file_path): #进行遍历
            dicts.append(Get_lrcs.lrc_to_dict(str(file_path),str(files))) #向dicts列表追加字典,file_path是文件夹路径,files是遍历的文件名
        return dicts  #返回列表
class Lrc(Get_lrcs): #继承Get_lrcs类
    kkk=Get_lrcs.get_lrc_name("./music_lrcs/")#歌词所在文件夹的路径
    print(kkk[0]) #预览列表里获取到的第一个字典,可以把用for遍历列表内的每一个字典
    for i,j in kkk[0].items(): #预览效果 i表示字典的key值,j表示字典的vlaue值
        print(i,j)

代码图片:

效果图:

本文地址:https://blog.csdn.net/weixin_45816571/article/details/107142351

《使用python将歌词文件(.lrc文件)转换成字典及遍历获取文件夹内所有lrc文件并以lrc格式显示出来.doc》

下载本文的Word格式文档,以方便收藏与打印。