Python 读取文本文件(gcode)并使用坐标

Python 读取文本文件(gcode)并使用坐标,python,Python,我试图读取一个gcode文件并使用上面的坐标。我以前做过,但现在似乎不起作用,我被卡住了 Gcode示例: G1 F1300 X195 Y97.5 E62.70186 G0 F3000 X195 Y100 G1 F1300 X95 Y100 E125.40371 G0 F3000 X95 Y102.5 G1 F1300 X195 Y102.5 E188.10557 G0 F3000 X195 Y105 G1 F1300 X95 Y105 E250.80742 G0 F3000 X95 Y107.

我试图读取一个gcode文件并使用上面的坐标。我以前做过,但现在似乎不起作用,我被卡住了

Gcode示例:

G1 F1300 X195 Y97.5 E62.70186
G0 F3000 X195 Y100
G1 F1300 X95 Y100 E125.40371
G0 F3000 X95 Y102.5
G1 F1300 X195 Y102.5 E188.10557
G0 F3000 X195 Y105
G1 F1300 X95 Y105 E250.80742
G0 F3000 X95 Y107.5
G1 F1300 X195 Y107.5 E313.50928
G0 F3000 X195 Y110
G1 F1300 X95 Y110 E376.21113
G0 F3000 X95 Y112.5
G1 F1300 X175 Y112.5 E426.37261
G0 F3000 X175 Y115
G1 F1300 X95 Y115 E476.5341
G0 F3000 X95 Y117.5
我可以打印和写入所有行和单元格,但我需要获得
X
的值

这是我以前用来实现它的代码,但现在不行了。我错过了什么

with open("gcode.txt","r") as f:
    content = f.readlines()

for line in content:

    line = line.rstrip("\n")
    cells = line.split(" ")

    if line.startswith("G1"):
        x = float(cells[2].split("X")[1])
        print (x)
我得到的错误是:

  x = float(cells[2].split("X")[1])

IndexError: list index out of range
我们有
line=“G1 F1300 X175 Y112.5 E426.37261”

然后,
单元格=[“G1”、“F1300”、“X175”、“Y112.5”、“E426.37261”]

然后,
xcell=“X175”

然后,
split\u x\u cell=“[”,“175]”

split_x_cell[1] is the x-value.
您的文件中一定有一行不符合通常的模式。
尝试运行以下代码并查看打印的警告消息:

import sys

with open("gcode.txt","r") as f:
    content = f.readlines()

for line in content:
    try:
        line = line.rstrip("\n")
        cells = line.split(" ")

        if line.startswith("G1"):
            cells = line.split(" ")
            xcell = cells[2]
            split_x_cell = xcell.split("X")
            x_val = float(split_x_cell[1])
            print(x)
    except IndexError:
        print(
            40*"#",
            "WARNING",
            "Incorrectly formatted line was omitted",
            repr(line),
            file=sys.stderr,
            sep = "\n",
        )

这意味着您的文件中有一行与模式不匹配是的,这就是问题所在。现在我检测到了它。谢谢,有一些行与格式不符。这可能不是我第一次编写代码时测试的gcode发生的。谢谢
split_x_cell = xcell.split("X")
split_x_cell[1] is the x-value.
import sys

with open("gcode.txt","r") as f:
    content = f.readlines()

for line in content:
    try:
        line = line.rstrip("\n")
        cells = line.split(" ")

        if line.startswith("G1"):
            cells = line.split(" ")
            xcell = cells[2]
            split_x_cell = xcell.split("X")
            x_val = float(split_x_cell[1])
            print(x)
    except IndexError:
        print(
            40*"#",
            "WARNING",
            "Incorrectly formatted line was omitted",
            repr(line),
            file=sys.stderr,
            sep = "\n",
        )