Python Forum
Is there a better way? Python parsing - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Is there a better way? Python parsing (/thread-30363.html)



Is there a better way? Python parsing - tlewick1 - Oct-17-2020

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.


RE: Is there a better way? Python parsing - bowlofred - Oct-17-2020

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'