Would I need regular expressions in Python to do this?


#1

What I’m attempting to do is to take some lines of G-code and convert them into comma delimited values that I can use in Rhino. For example, this…

N11 X135.041Y75.644Z91.874
N12 X136.497Y74.605Z91.812
N13 X138.258Y74.294Z91.749
N14 X139.982Y74.772Z91.687

would become this…

135.041,75.644,91.874
136.497,74.605,91.812
138.258,74.294,91.749
139.982,74.772,91.687

I would also need to filter out any characters that are not linear moves, like this:

N1 G21
N2 G0G17G40G80
N3 T7M6
N4 G0G54
N5 S3500M3
N6 M8

I have a Rhinoscript that does this now, but my experience with Python so far is only enough to make me think that there is probably an easier way to do this than to mimic the Rhinoscript idea.

Thanks in advance for any pointers that may help,

Dan


(Steve Baer) #2

Knowing almost nothing about gcode and using basic string functions you could do something like the following:

import rhinoscriptsyntax as rs
gcode = """
N1 G21
N2 G0G17G40G80
N3 T7M6
N4 G0G54
N5 S3500M3
N6 M8
N11 X135.041Y75.644Z91.874
N12 X136.497Y74.605Z91.812
N13 X138.258Y74.294Z91.749
N14 X139.982Y74.772Z91.687"""

lines = gcode.splitlines()

for line in lines:
    if not line: continue
    n, command = line.split(' ')
    if command.startswith('X') and command.find('Y')>0 and command.find('Z')>0:
        point_string = command[1:].replace("Y",",").replace("Z",",")
        point = rs.coerce3dpoint(point_string)
        print "point", point
    else:
        print "command", command

#3

Hi Steve,

I actually understand most of that! I must be making progress!

Just one question. What does the “n” do in the line: n, command = line.split(’ ')?

Thanks for your help,

Dan


#4

This is an example of “tuple unpacking”. You can have functions that output multiple objects (in the form of a tuple) and assign them to multiple variables… n, command = line.split(' ') assumes that there will be exactly be two strings returned by split, the first will be assigned to n, the second to command. The n, command is an “implied tuple”: really (n, command).

The problem here is that the number of variables must always correspond to the number of objects returned; otherwise the unpacking will fail. If there are more or less returned strings in the output - say there is a second space somewhere, which will make it split into three substrings - the function will fail, so it’s not extremely robust with unknown data.

–Mitch


(Steve Baer) #5

You can also try placing a breakpoint on that line to see what it does :smiley:


#6

Thanks Mitch.


#7

Yes, that is a good idea.

Thanks,

Dan