|
|
- # -*- coding: utf-8 -*-
- """
- NC/G代码文件分割工具
- - 以 OXXXX 开头,以 M30 结束
- - 每个分割文件以该程序第一行的字符作为文件名
- """
- import os
- import re
- def sanitize_filename(name: str) -> str:
- """清理文件名中的非法字符(Windows 不允许 \ / : * ? " < > |)"""
- # 替换非法字符为下划线
- name = re.sub(r'[\\/:*?"<>|]', '_', name)
- # 去除首尾空白和点
- name = name.strip(' .')
- # 限制长度,避免文件名过长
- return name[:100] if name else 'unnamed'
- def split_nc_file(input_path: str, output_dir: str = None) -> list:
- # 默认输出目录:输入文件同目录下的 split_output
- if output_dir is None:
- output_dir = os.path.join(os.path.dirname(os.path.abspath(input_path)), 'split_output')
- os.makedirs(output_dir, exist_ok=True)
- # 多编码兼容读取
- content = None
- for enc in ('utf-8', 'gbk', 'gb2312', 'latin-1'):
- try:
- with open(input_path, 'r', encoding=enc) as f:
- content = f.read()
- break
- except UnicodeDecodeError:
- continue
- if content is None:
- raise ValueError("无法识别文件编码")
- lines = content.splitlines()
- generated = []
- current_lines = []
- first_line = None
- in_program = False
- for line in lines:
- stripped = line.strip()
- # 检测程序开始:行首 O + 数字
- if re.match(r'^O\d+', stripped, re.IGNORECASE):
- in_program = True
- current_lines = [line]
- first_line = stripped # 记录第一行(去掉首尾空白)
- continue
- if in_program:
- current_lines.append(line)
- # 检测程序结束:行中包含 M30
- if re.search(r'M30', stripped, re.IGNORECASE):
- # 用第一行字符作为文件名
- filename = sanitize_filename(first_line) + '.nc'
- out_path = os.path.join(output_dir, filename)
- # 处理重名:自动加序号
- counter = 1
- while os.path.exists(out_path):
- name, ext = os.path.splitext(filename)
- out_path = os.path.join(output_dir, f"{name}_{counter}{ext}")
- counter += 1
- # 写入文件
- with open(out_path, 'w', encoding='utf-8') as f:
- f.write('\n'.join(current_lines) + '\n')
- generated.append(out_path)
- print(f"已生成: {out_path}")
- # 重置状态
- in_program = False
- current_lines = []
- first_line = None
- return generated
- if __name__ == '__main__':
- path = input("请输入文件路径: ").strip().strip('"')
- if not os.path.isfile(path):
- print(f"文件不存在: {path}")
- else:
- results = split_nc_file(path)
- print(f"\n分割完成,共生成 {len(results)} 个文件。")
复制代码 |
|