【问题标题】:Using re.compile function to parse a gcode file line by line in Python使用 re.compile 函数在 Python 中逐行解析 gcode 文件
【发布时间】:2020-06-01 15:57:16
【问题描述】:

我正在逐行解析一个 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)

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

【问题讨论】:

  • 你可以用 perl 代替 python 吗? IE。 perl -ne "print $. if /M622/" your_data_file
  • 是的,我可以...但是由于有一些同事已经知道一点 Python,我决定走这条路。

标签: python regex python-3.x parsing g-code


【解决方案1】:

你可以这样做:

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)

【讨论】:

    猜你喜欢
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    相关资源
    最近更新 更多