Python Forum

Full Version: Is there a better way? Python parsing
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I've written the following code:
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.0003
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.
Why not just keep the minus symbol with your number? Then, I think you don't care if it's positive or negative, you just print it.

res = r'X(-?\d+\.\d*)
>>> re.search(r'X(-?\d+\.\d*)', "Z1.371 Y-1.279 X-0.0003").groups()[0]
'-0.0003'
>>> re.search(r'X(-?\d+\.\d*)', "Z1.371 Y-1.279 X0.0003").groups()[0]
'0.0003'