车载音乐时间戳
大约 4 分钟
处理汽车车载 U 盘音乐歌词显示问题
注:前面的两个版本功能不太齐全,要保证文件夹中只有 .lrc
文件。
如果想体验完整版可以直接跳转到最后两个版本。
初级版
music1
文件是处理前的文件夹,music2
是处理后的文件夹
提取文件名
首先在 music1
文件夹中,新建 music.txt
输入下面代码,然后另存为 music.bat
DIR *.* /B >LIST.TXT
修改时间代码
只需修改代码中处理文件前后的两个 文件夹路径
,和更改 第9行
的 歌曲名
即可。
import os
def check_and_delete_digit(line):
if len(line) >= 10 and line[9].isdigit():
line = line[:9] + line[10:]
else:
pass
return line
input_filename = "A.I.N.Y..lrc" # 歌曲名
output_filename = input_filename
# 读取文件
file_path = "D:/桌面/music1/" + input_filename # 文件名
output_lines = []
with open(file_path, encoding="utf8") as file:
for line in file:
line = line.strip()
line = check_and_delete_digit(line)
output_lines.append(line)
# 将处理后的内容写入新文件
output_file_path = os.path.join("D:/桌面/music2/", output_filename)
with open(output_file_path, "w", encoding="utf8") as output_file:
output_file.write("\n".join(output_lines))
print(input_filename + "文件处理完成!")
完善版
该版本只要修改 input_folder_path
和 output_folder_path
两个变量即可
import os
def check_and_delete_digit(line):
if len(line) >= 10 and line[9].isdigit():
line = line[:9] + line[10:]
else:
pass
return line
def delete_timecode(lines):
start_index = -1
for i, line in enumerate(lines):
if "[00:00.00]" in line:
start_index = i
break
if start_index != -1:
return lines[start_index:]
else:
return lines
input_folder_path = "D:\桌面\music1"
output_folder_path = "D:\桌面\music2"
for filename in os.listdir(input_folder_path):
file_path = os.path.join(input_folder_path, filename)
output_lines = []
with open(file_path, "r", encoding="utf8") as file:
for line in file:
line = line.strip()
line = check_and_delete_digit(line)
output_lines.append(line)
output_lines = delete_timecode(output_lines)
output_file_path = os.path.join(output_folder_path, filename)
with open(output_file_path, "w", encoding="utf8") as output_file:
output_file.write("\n".join(output_lines))
print("文件 {} 已处理完成!".format(filename))
print("所有文件已处理完成!")
升级版
使用的是 python
自带的图形化界面 tkinter
,无需其它安装操作,拿来即用。添加了如下功能:
- 只处理文件夹中后缀为".lrc"的文件
import os
import re
import tkinter as tk
from tkinter import filedialog, messagebox
# 功能
def replace_timestamps(input_file, output_file):
with open(input_file, "r", encoding="utf8") as file:
text = file.read()
modified_text = re.sub(r'(\[\d{2}:\d{2}\.\d)\]', lambda x: x.group(1) + '0]', text)
with open(output_file, "w", encoding="utf8") as file:
file.write(modified_text)
def check_and_delete_digit(line):
if len(line) >= 10 and line[9].isdigit():
line = line[:9] + line[10:]
else:
pass
return line
def delete_timecode(lines):
start_index = -1
for i, line in enumerate(lines):
if "[00:00." in line:
start_index = i
break
if start_index != -1:
lines = [re.sub(r'^.*(\[00:00\.\d+\])', r'\1', line) if "[00:00." in line else line for line in lines[start_index:]]
return lines
# 功能汇总
def process_files():
input_folder_path = input_folder_path_entry.get()
output_folder_path = output_folder_path_entry.get()
for filename in os.listdir(input_folder_path):
if filename.endswith('.lrc'):
file_path = os.path.join(input_folder_path, filename)
output_lines = []
replace_timestamps(file_path, file_path) # 先替换时间戳
with open(file_path, "r", encoding="utf8") as file:
for line in file:
line = line.strip()
line = check_and_delete_digit(line)
output_lines.append(line)
output_lines = delete_timecode(output_lines)
output_file_path = os.path.join(output_folder_path, filename)
with open(output_file_path, "w", encoding="utf8") as output_file:
output_file.write("\n".join(output_lines))
print("文件 {} 已处理完成!".format(filename))
messagebox.showinfo("处理完成", "所有文件已处理完成!")
root.destroy()
# 图形界面
def browse_input_folder():
folder_path = filedialog.askdirectory()
input_folder_path_entry.delete(0, tk.END)
input_folder_path_entry.insert(0, folder_path)
def browse_output_folder():
folder_path = filedialog.askdirectory()
output_folder_path_entry.delete(0, tk.END)
output_folder_path_entry.insert(0, folder_path)
# 主界面
root = tk.Tk()
root.title("文件处理程序")
input_folder_label = tk.Label(root, text="输入文件夹路径:")
input_folder_label.grid(row=0, column=0, padx=5, pady=5)
input_folder_path_entry = tk.Entry(root, width=50)
input_folder_path_entry.grid(row=0, column=1, padx=5, pady=5)
browse_input_button = tk.Button(root, text="浏览", command=browse_input_folder)
browse_input_button.grid(row=0, column=2, padx=5, pady=5)
output_folder_label = tk.Label(root, text="输出文件夹路径:")
output_folder_label.grid(row=1, column=0, padx=5, pady=5)
output_folder_path_entry = tk.Entry(root, width=50)
output_folder_path_entry.grid(row=1, column=1, padx=5, pady=5)
browse_output_button = tk.Button(root, text="浏览", command=browse_output_folder)
browse_output_button.grid(row=1, column=2, padx=5, pady=5)
process_button = tk.Button(root, text="处理文件", command=process_files)
process_button.grid(row=2, column=1, padx=5, pady=5)
root.mainloop()
最终版
对处理界面进行了美化,个人感觉 升级版
的界面太过模糊,于是使用了 PyQt5
进行了美化,使界面更加清除。还增加了如下功能。
- 添加计数标签到布局中,显示处理完成的文件数
首先要先安装 PyQt5
框架,使用如下命令:
pip install PyQt5 -i https://pypi.douban.com/simple
接下来便是完整的代码:
import os
import re
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel, QLineEdit, QFileDialog, QMessageBox
class FileProcessor(QWidget):
# 界面
def __init__(self):
super().__init__()
self.initUI()
self.file_count = 0
def initUI(self):
self.input_folder_path_entry = QLineEdit()
self.output_folder_path_entry = QLineEdit()
self.select_input_button = QPushButton("选择输入文件夹")
self.select_input_button.clicked.connect(self.selectInputFolder)
self.select_output_button = QPushButton("选择输出文件夹")
self.select_output_button.clicked.connect(self.selectOutputFolder)
self.process_button = QPushButton("开始处理")
self.process_button.clicked.connect(self.processFiles)
self.count_label = QLabel("已完成文件数量: 0")
vbox = QVBoxLayout()
hbox1 = QHBoxLayout()
hbox1.addWidget(QLabel("输入文件夹路径: "))
hbox1.addWidget(self.input_folder_path_entry)
hbox1.addWidget(self.select_input_button)
vbox.addLayout(hbox1)
hbox2 = QHBoxLayout()
hbox2.addWidget(QLabel("输出文件夹路径: "))
hbox2.addWidget(self.output_folder_path_entry)
hbox2.addWidget(self.select_output_button)
vbox.addLayout(hbox2)
vbox.addWidget(self.process_button)
vbox.addWidget(self.count_label) # 添加计数标签到布局
self.setLayout(vbox)
self.setWindowTitle('文件处理工具')
self.show()
def selectInputFolder(self):
folder_path = str(QFileDialog.getExistingDirectory(self, "选择输入文件夹"))
self.input_folder_path_entry.setText(folder_path)
def selectOutputFolder(self):
folder_path = str(QFileDialog.getExistingDirectory(self, "选择输出文件夹"))
self.output_folder_path_entry.setText(folder_path)
# 功能
def replaceTimestamps(self, input_file, output_file):
with open(input_file, "r", encoding="utf8") as file:
text = file.read()
modified_text = re.sub(r'(\[\d{2}:\d{2}\.\d)\]', lambda x: x.group(1) + '0]', text)
with open(output_file, "w", encoding="utf8") as file:
file.write(modified_text)
def checkAndDeleteDigit(self, line):
if len(line) >= 10 and line[9].isdigit():
line = line[:9] + line[10:]
else:
pass
return line
def deleteTimecode(self, lines):
start_index = -1
for i, line in enumerate(lines):
if "[00:00." in line:
start_index = i
break
if start_index != -1:
lines = [re.sub(r'^.*(\[00:00\.\d+\])', r'\1', line) if "[00:00." in line else line for line in lines[start_index:]]
return lines
def processFiles(self):
input_folder_path = self.input_folder_path_entry.text()
output_folder_path = self.output_folder_path_entry.text()
for filename in os.listdir(input_folder_path):
if filename.endswith('.lrc'):
file_path = os.path.join(input_folder_path, filename)
output_lines = []
self.replaceTimestamps(file_path, file_path)
with open(file_path, "r", encoding="utf8") as file:
for line in file:
line = line.strip()
line = self.checkAndDeleteDigit(line)
output_lines.append(line)
output_lines = self.deleteTimecode(output_lines)
output_file_path = os.path.join(output_folder_path, filename)
with open(output_file_path, "w", encoding="utf8") as output_file:
output_file.write("\n".join(output_lines))
print("文件{} 已处理完成!".format(filename))
self.file_count += 1
self.count_label.setText("已完成文件数量: {}".format(self.file_count))
self.process_button.setText("处理完成,所有文件已处理完成!")
self.process_button.setDisabled(True)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
ex = FileProcessor()
sys.exit(app.exec_())