I have a program that grabs numbers from a .txt file and puts it into an array. The problem is that the numbers are not isolated or ordered. The .txt file looks like this:
G40 Z=10
A=30 X10 Y50
A=30 X40 Y15
A=50 X39 Y14
G40 Z=11
A=30 X10 Y50
A=30 X40 Y15
A=50 X39 Y14
The output should be a new .txt file that has the following array format
X Y Z
10 50 10
40 15 10
39 14 10
10 50 11
40 15 11
39 14 11
This is what I have done so far, although I'm not sure how to write my output to a new file...
inputfile = open('circletest1.gcode' , 'r')
def find_between( s, first, last ):
try:
start = s.index( first ) + len( first )
end = s.index( last, start )
return s[start:end]
except ValueError:
return ""
for i in range(203): inputfile.next() # skip first 203 lines
while True:
my_text = inputfile.readline()
z = find_between(my_text, "Z =", " ")
x = find_between(my_text, "X", " ")
y = find_between(my_text, "Y", " ")
print(x ," ", y, " ", z)
if not my_text:break
inputfile.close()
For a while I was receiving indentation errors, but I believe that I have fixed that problem. Now the error message that I am getting is "Value error: Mixing iteration and read methods would lose data".
I am not sure where to go from here, nor am I sure how to import my results into another separate new txt file.
Also, in my code, is there a way to preserve the z value outside of the loop until a new z value is assigned?
解决方案
If I understand correctly, you want to combine the Z value from the lines that start with G with the X and Y values from the following lines (until the next G line).
If so, I'd use a single loop, printing only on the lines that start with A and just saving the new Z value on the lines that start with G. I'd do the line parsing with regex, but you could use simple string manipulation if you wanted to (I'd split and then skip the first letter or letters of the relevant items).
import itertools
import re
z = None
with open('circletest1.gcode') as input_file:
for line in itertools.islice(203, None): # islice to skip the first 203 lines
if line.startswith("G"):
z = re.search(r"Z=(\d+)", line).group(1)
elif line.startswith("A"):
x, y = re.search(r"X(\d+) Y(\d+)", line).groups()
print(x, y, z)