原来写了个py脚本,用于重命名从qq音乐下载的米哈游的音乐(ogg、mp3、flac均有)
Python
import os
import re
# QQ音乐
prog = re.compile(r"(.*\\)(.*) - (.*)( \[.*\])(\..*)")
# 网易云
# prog = re.compile(r"(.*) - (.*)")
def concat(*args, sep=""):
return sep.join(args)
for curDir, dirs, files in os.walk(r"D:\LanguageLearning\python\music"):
for file in files:
# qq
if file[-5:] == "].mp3" or file[-5:] == "].ogg" or file[-6:] == "].flac":
# 网易
# if (file[-3:] not in {"exe",".py","cmd","bat"}):
name = os.path.join(curDir, file)
# print(name)
# print("")
# QQ
new_name_list = prog.split(name, 5)
new_name = (
'"' + concat(new_name_list[1], new_name_list[3], new_name_list[5]) + '"'
)
name = '"' + name + '"'
print(new_name)
# ---
# 网易
# new_name_list = prog.split(name, 2)
# print(new_name_list)
# new_name = os.path.split(os.path.realpath(__file__))[0] + "\\" + new_name_list[2]
try:
# qq
os.renames(name, new_name)
# 网易
# os.renames(name, new_name)
except: # noqa: E722
os.remove(name[1:-1])
print("Success!", end="\n\n")
邪门玩意,明明py3.10都没问题的,也没看着py更新了与文件重命名相关的函数啊,怎么自从更新到py最新版本3.12突然就寄了……
典型表现就是运行到一半突然卡住,也不报错,也不提示,也不崩溃。任务管理器python占用cpu:0%-0.4%(在我的电脑上很正常),内存长久无变化,调试了一番硬是没发现问题出在哪里……明明一切都完美运行,然后突然毫无征兆的,进度就卡死在那里了……真是邪门……
正好我对Python的运行效率头大很久了,Rust又不太会用,于是直接决定用自己不怎么熟悉的cpp直接重写一个……
得益于Cpp糟糕max的UTF8(CJK)支持,我从昨晚12点写到3点,又从今天11点写到刚刚终于弄明白了……本来咱就不咋会cpp,还得想着做CJK兼容……真是服了cpp了
好在最后自己憋出来了……累死,AI用了吗?如用。解答的东西狗屁不通,思路都不对……
放小众留个痕迹吧,万一以后我手贱删了还有地方找,也懒得上传github了
cpp
#include "locale.h"
#include "wchar.h"
#include <filesystem>
#include <iostream>
#include <regex>
#include <string>
#include <windows.h>
using namespace std;
using namespace filesystem;
int main() {
/*Set local of the rigion to avoid error caused by wrong coding*/
std::setlocale(LC_ALL, "en_US.utf8");
/*Init file path*/
path file_dir = L"(D:\\LanguageLearning\\python\\music)";
if (!exists(file_dir))
exit(1);
/*Start regex*/
wsmatch regex_result_group;
wregex reg(L"(.*\\\\)(.*) - (.*)( \\[.*\\])(\\.)(ogg|mp3|flac|wav)");
/*Start to enum the dir*/
directory_iterator list(file_dir);
for (auto &it : list) {
wstring temp = it.path().wstring();
/*if path could match the regex, set the new_name*/
if (regex_search(temp, regex_result_group, reg)) {
wstring result = regex_result_group[1].str() +
regex_result_group[3].str() + L"." +
regex_result_group[6].str();
wstring original_name = regex_result_group[0].str();
wstring brief_name = regex_result_group[3].str();
/*Try to rename*/
if (0 != _wrename(original_name.c_str(), result.c_str())) {
wcout << "Error" << brief_name << endl;
} else {
wcout << "Successfully! " << brief_name << endl << endl;
}
}
}
return 0;
}
(注:编译参数:-std=c++23 -Wall -Werror -O3 -pthread
,请使用std23版本)
二编:
并且终于在大佬的分析下整明白了python为啥会崩(但是还是说上个版本没崩 ),大抵就是错误的引号导致的rename和remove函数崩溃
在ai的帮助下改用rust全面重写,彻底解决了cpp的中文传参问题(我就没整明白过)
三编
Rust重写了一点点,增加了一点奇怪的路径支持功能
四编,改了rust的一点点冗余
main.rs
use regex::Regex;
use std::{env, fs, path::PathBuf};
fn main() {
let mut args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!(
"\nRegex QQMusic Renamer version 1.6\n\nUsage:\n{} <directory>\n{} <files>\n",
&args[0], &args[0]
);
return;
}
let input_path: PathBuf = PathBuf::from(&args[1]);
let (input_is_dir, checked_path) = check_path_dir(input_path);
if input_is_dir {
println!("Enum {:?} ...", checked_path);
for files in fs::read_dir(&checked_path.as_path()).unwrap() {
rename_files(&files.unwrap().path());
}
} else {
args.remove(0);
for i in args {
rename_files(&PathBuf::from(&i));
}
}
}
fn check_path_dir(mut path_to_check: PathBuf) -> (bool, PathBuf) {
path_to_check = if path_to_check.ends_with("\"") {
PathBuf::from(path_to_check.to_string_lossy().strip_suffix("\"").unwrap())
} else {
path_to_check
};
if !path_to_check.exists() {
panic!("{:?} does not exist.", path_to_check.to_str());
}
(path_to_check.is_dir(), path_to_check)
}
fn get_new_name(regex: Regex, original_name: &str) -> &str {
regex
.captures(original_name)
.unwrap()
.get(2)
.unwrap()
.as_str()
}
fn rename_files(each_path: &PathBuf) {
let reg = Regex::new(r"(.*) - (.*)( \[.*)").unwrap();
//File name example: "HOYO-MiX - 枫丹 Fontaine [qmmc2].flac"
if !each_path.is_dir() {
let ext_list = ["ogg", "mp3", "flv", "flac", "wav", "mgg2", "mgg", "mflac"];
let file_name = each_path.file_stem().unwrap().to_str().unwrap();
let file_ext = each_path.extension().unwrap().to_str().unwrap();
let dir_path = each_path.parent().unwrap().to_str().unwrap();
if ext_list.contains(&file_ext) && reg.is_match(file_name) {
let new_file_name = get_new_name(reg, file_name);
let new_file_path =
PathBuf::from(dir_path).join(new_file_name.to_string() + "." + file_ext);
fs::rename(each_path, new_file_path).unwrap();
println!("Renamed {} to {}", file_name, new_file_name);
}
}
}
Cargo.toml
[package]
name = "_regex_qqmusic_renamer"
version = "1.3.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[profile.release]
lto = true
codegen-units = 1
opt-level = "z"
strip = true
[dependencies]
regex = { version = "1.10.2" }
winapi = { version = "0.3.9" }