Python Forum
Is there a better way? Python parsing
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is there a better way? Python parsing
#1
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.
Reply
#2
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'
tlewick1 likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Parsing link from html tags with Python Melcu54 0 1,601 Jun-14-2021, 09:25 AM
Last Post: Melcu54
  XML Parsing in python aarushprathap 2 2,280 Jul-11-2020, 09:29 AM
Last Post: j.crater
  python realtime parsing logs anna 2 2,808 Jul-05-2020, 06:36 AM
Last Post: anna
  Parsing Text file having repeated value key pair using python manussnair 3 3,267 Aug-04-2018, 11:48 PM
Last Post: micseydel
  Python file parsing, can't catch strings in new line Philia 5 3,943 Apr-29-2018, 01:09 PM
Last Post: snippsat
  Parsing csv using python Firstname_Lastname 4 3,926 Sep-03-2017, 06:26 PM
Last Post: Larz60+
  Text file parsing with python and with a list in grammar pitanga 2 3,215 Aug-31-2017, 02:21 PM
Last Post: pitanga

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020