使用 re.compile 函数在 Python 中逐行解析 gcode 文件



我正在逐行解析一个gcode文件(位于f_path中(,搜索给定的字符串。该字符串("M622"(在整个文本文件中显示为单个文本,其结构如下所示:

GCODE 文件

M622; arm the Lasers
M610 S0 A80 B0 C0 ; allocate feeders
T0 ; set active extruder
G92 E0 ; set active extruder to 0
G28 XY ; home X and Y
G28 X ; home x
G90 ; absolute
G0 F3000 X35 Y5 S255 ; edge of plate
G92 X0 Y0 Z-2 ; local home
G0 Z0 ; drop Z 

最后,我希望代码返回找到字符串的行号。

法典

rgx_start = re.compile(r'M622') # String to be searched: "M622"
with open (f_path, 'rt') as txtfile:
line = txtfile.readline()
line_i = 0  # Counter of each line in the original text file
hdr_start = 0 # Variable to store the line number where the header starts
while line:  # Reading each line as a string
while rgx_start.search(line) != None: # No "M622" is found => move to the next line
line_i += 1 # The line counter is set to the next line
hdr_start = line_i # When "M622" is found
print('First line: ',hdr_start)

当我运行上面的代码时,我进入了一个无限循环。有什么建议吗?

你可以做:

import re
rgx_start = re.compile(r'M622') 
with open('gt.dat','r') as textfile:
for i,line in enumerate(textfile.readlines()):
if  rgx_start.search(line):
line = i
break  # since you said that it appears once
print(line)

最新更新