Oct-17-2020, 04:40 PM
I've written the following code:
The output would be: Z1.371 Y-1.279 X-0.0003 U-0.0003
This works, but now I'm expanding on the idea and it seems like I'm doing double the work dealing with the negative numbers.
Is there a better way to deal with the negative? My new program will need to format the text, arranging the strings into arrays where the data types = float.
import re
res_pos = r'(X)(\d+\.\d*)'
res_neg = r'(X-)(\d+\.\d*)'
def grab_pos(line, pattern=res_pos):
result = re.search(pattern, line)
num = result.group(2) if result else None
return num
def grab_neg(line, pattern=res_neg):
result = re.search(pattern, line)
num = result.group(2) if result else None
return num
with open ('GCODE.txt', 'rt') as infile, open('GCODE_OUT.txt', 'w') as outfile:
for line in infile:
result_pos = grab_pos(line)
result_neg = grab_neg(line)
if result_pos:
subs = re.sub(r'(X)(\d+\.\d*)', 'X'+result_pos+' U'+result_pos, line)
outfile.write(subs)
elif result_neg:
subs = re.sub(r'(X-)(\d+\.\d*)', 'X-'+result_neg+' U-'+result_neg, line)
outfile.write(subs)
else:
outfile.write(line)An example of the input text might be: Z1.371 Y-1.279 X-0.0003The output would be: Z1.371 Y-1.279 X-0.0003 U-0.0003
This works, but now I'm expanding on the idea and it seems like I'm doing double the work dealing with the negative numbers.
Is there a better way to deal with the negative? My new program will need to format the text, arranging the strings into arrays where the data types = float.
