diff --git a/remove_lf_m3t.py b/remove_lf_m3t.py new file mode 100644 index 0000000..0ca0cc8 --- /dev/null +++ b/remove_lf_m3t.py @@ -0,0 +1,67 @@ +import os + + +def remove_lf(text: str) -> str: + texts = [i.lstrip() for i in text.replace("\\n", "\n").splitlines()] + return ''.join(texts) + + +def process_m3t(m3t_path): + lines = [] + line_num = 0 + for line in open(m3t_path, "r", encoding="utf-8"): + line = line.strip() + line = line.replace('\u200b', '') # 移除零宽空格 + if line_num == 0: + line = line.lstrip("\ufeff") # 移除可能的BOM + line_num += 1 + if line.startswith("●") or line.startswith("△") or line.startswith("○"): + if line.startswith("○ NAME:"): + continue + data = line[1:].strip() + ndata = remove_lf(data) + if data != ndata: + print(f"{m3t_path}:{line_num}: {data} -> {ndata}") + line = line[0] + " " + ndata + lines.append(line) + return lines + + +def save_lines(m3t_path, lines): + with open(m3t_path, "w", encoding="utf-8") as f: + for line in lines: + f.write(line + "\n") + + +def process_m3t_file(m3t_path, target_path=None): + lines = process_m3t(m3t_path) + if target_path is None: + save_lines(m3t_path, lines) + else: + os.makedirs(os.path.dirname(target_path), exist_ok=True) + save_lines(target_path, lines) + + +def recursive_process_m3t(m3t_path, target_path=None, ext=".txt"): + for root, dirs, files in os.walk(m3t_path): + for file in files: + if not file.lower().endswith(ext): + continue + full_path = os.path.join(root, file) + output_path = None + if target_path is not None: + output_path = os.path.join(target_path, file) + process_m3t_file(full_path, output_path) + + +if __name__ == "__main__": + from argparse import ArgumentParser + parser = ArgumentParser(description="Post-process M3T files.") + parser.add_argument("m3t_path", help="Path to M3T file/directory.") + parser.add_argument("target_path", nargs="?", default=None, help="Path to save processed M3T file/directory. If not specified, overwrite original files.") + parser.add_argument("--ext", default=".txt", help="File extension to process in directory mode.") + args = parser.parse_args() + if os.path.isdir(args.m3t_path): + recursive_process_m3t(args.m3t_path, args.target_path, args.ext) + else: + process_m3t_file(args.m3t_path, args.target_path)