找回密码
 立即注册

QQ登录

只需一步,快速开始

微信扫码登录

搜索
查看: 24|回复: 0

[经典资料] 用Python写的一个脚本,机床拷贝的文件ALL-PROG.TXT分割成独立的NC文件

[复制链接]

2

主题

0

回帖

33

积分

列兵

积分
33
发表于 3 小时前 | 显示全部楼层 |阅读模式
  1. # -*- coding: utf-8 -*-
  2. """
  3. NC/G代码文件分割工具
  4. - 以 OXXXX 开头,以 M30 结束
  5. - 每个分割文件以该程序第一行的字符作为文件名
  6. """

  7. import os
  8. import re


  9. def sanitize_filename(name: str) -> str:
  10.     """清理文件名中的非法字符(Windows 不允许 \ / : * ? " < > |)"""
  11.     # 替换非法字符为下划线
  12.     name = re.sub(r'[\\/:*?"<>|]', '_', name)
  13.     # 去除首尾空白和点
  14.     name = name.strip(' .')
  15.     # 限制长度,避免文件名过长
  16.     return name[:100] if name else 'unnamed'


  17. def split_nc_file(input_path: str, output_dir: str = None) -> list:
  18.     # 默认输出目录:输入文件同目录下的 split_output
  19.     if output_dir is None:
  20.         output_dir = os.path.join(os.path.dirname(os.path.abspath(input_path)), 'split_output')
  21.     os.makedirs(output_dir, exist_ok=True)

  22.     # 多编码兼容读取
  23.     content = None
  24.     for enc in ('utf-8', 'gbk', 'gb2312', 'latin-1'):
  25.         try:
  26.             with open(input_path, 'r', encoding=enc) as f:
  27.                 content = f.read()
  28.             break
  29.         except UnicodeDecodeError:
  30.             continue
  31.     if content is None:
  32.         raise ValueError("无法识别文件编码")

  33.     lines = content.splitlines()
  34.     generated = []

  35.     current_lines = []
  36.     first_line = None
  37.     in_program = False

  38.     for line in lines:
  39.         stripped = line.strip()

  40.         # 检测程序开始:行首 O + 数字
  41.         if re.match(r'^O\d+', stripped, re.IGNORECASE):
  42.             in_program = True
  43.             current_lines = [line]
  44.             first_line = stripped   # 记录第一行(去掉首尾空白)
  45.             continue

  46.         if in_program:
  47.             current_lines.append(line)

  48.             # 检测程序结束:行中包含 M30
  49.             if re.search(r'M30', stripped, re.IGNORECASE):
  50.                 # 用第一行字符作为文件名
  51.                 filename = sanitize_filename(first_line) + '.nc'
  52.                 out_path = os.path.join(output_dir, filename)

  53.                 # 处理重名:自动加序号
  54.                 counter = 1
  55.                 while os.path.exists(out_path):
  56.                     name, ext = os.path.splitext(filename)
  57.                     out_path = os.path.join(output_dir, f"{name}_{counter}{ext}")
  58.                     counter += 1

  59.                 # 写入文件
  60.                 with open(out_path, 'w', encoding='utf-8') as f:
  61.                     f.write('\n'.join(current_lines) + '\n')

  62.                 generated.append(out_path)
  63.                 print(f"已生成: {out_path}")

  64.                 # 重置状态
  65.                 in_program = False
  66.                 current_lines = []
  67.                 first_line = None

  68.     return generated


  69. if __name__ == '__main__':
  70.     path = input("请输入文件路径: ").strip().strip('"')
  71.     if not os.path.isfile(path):
  72.         print(f"文件不存在: {path}")
  73.     else:
  74.         results = split_nc_file(path)
  75.         print(f"\n分割完成,共生成 {len(results)} 个文件。")
复制代码
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

咨询QQ:1359218528|发帖须知!|Archiver|手机版|UG爱好者论坛 ( 京ICP备10217105号-2 )

GMT+8, 2026-8-12 20:32

Powered by Discuz! X3.5 Licensed

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表