Repository navigation
Expand file tree
/
Copy pathparser.py
More file actions
53 lines (42 loc) · 1.58 KB
/
Copy pathparser.py
File metadata and controls
53 lines (42 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import re
# Matches a letter followed by a number (int or float, optionally negative)
# e.g. "G81", "X-50.", "F1000."
WORD_RE = re.compile(r'([A-Za-z])(-?\d*\.?\d+)')
def parse_line(raw_line):
"""
Turn one line of G-code into a structured dict.
Returns None for blank lines, '%' markers, or pure comment lines.
"""
line = raw_line.strip()
if not line or line == '%':
return None
# Strip inline comments like (2D POCKET2) but keep them for reference
comment_match = re.search(r'\((.*?)\)', line)
comment = comment_match.group(1) if comment_match else None
code_part = re.sub(r'\(.*?\)', '', line).strip()
if not code_part:
# it was a comment-only line
return {'type': 'comment', 'comment': comment, 'raw': raw_line.rstrip()}
words = WORD_RE.findall(code_part)
result = {'type': 'code', 'comment': comment, 'raw': raw_line.rstrip(), 'g': [], 'm': []}
for letter, value in words:
letter = letter.upper()
num = float(value)
if letter == 'G':
result['g'].append(int(num))
elif letter == 'M':
result['m'].append(int(num))
elif letter == 'N':
result['n'] = int(num)
else:
result[letter] = num
return result
def parse_file(path):
"""Read an .nc file and return a list of parsed line-dicts (skipping None)."""
parsed = []
with open(path, 'r', errors='ignore') as f:
for raw_line in f:
result = parse_line(raw_line)
if result is not None:
parsed.append(result)
return parsed