[英]AttributeError: 'NoneType' object has no attribute 'text' - Python , BeautifulSoup Error
[英]Python "AttributeError: 'NoneType' object has no attribute" Error
我正在尝试编写一个 Python 代码来从“inkscape”gcode 文件中提取坐标,并将这些坐标用作另一个函数的输入。 就像我是编程和 Python 的初学者一样。 我写了很简单的几行,你可以在下面看到。 当我尝试运行代码时,我收到“AttributeError: 'NoneType' object has no attribute 'start'”错误。 我认为这是关于循环“xindex.start()”返回空值的乞求,所以我想我需要定义一个初始值,但我找不到如何去做。 示例代码仅适用于 X 值。
import re
with open("example.gcode", "r") as file:
for line in file:
if line.startswith('G00') or line.startswith('G01'): # find the lines which start with G00 and G01
xindex = re.search("[X]", line) # search for X term in the lines
xindex_number = int(xindex.start()) # find starting index number and convert it to int
gcode 的内部看起来像:
S1; endstops
G00 E0; no extrusion
G01 S1; endstops
G01 E0; no extrusion
G21; millimeters
G90; absolute
G28 X; home
G28 Y; home
G28 Z; home
G00 F300.0 Z20.000; pen park !!Zpark
G00 F2400.0 Y0.000; !!Ybottom
....
任何帮助表示赞赏
祝大家有个美好的一天
AttributeError: 'NoneType' object has no attribute 'start'
意味着您正在尝试在等于 None 的对象上调用.start()
。
您的代码正在寻找以 'G00' 或 'G01' 开头的第一行,在这种情况下将是该行: “G00 E0;无挤压” ,然后它试图找到字母 X 在该行中的位置。
在这种情况下,该行中不存在 'X',因此xindex = None
。 因此,您不能在不抛出错误的情况下调用xindex.start()
。 这就是错误告诉你的。
添加一个if
条件,它应该可以正常工作
import re
with open("example.gcode", "r") as file:
for line in file:
if line.startswith("G00") or line.startswith("G01"):
xindex = re.search("[X]", line)
# Check if a match was found
if xindex:
xindex_number = int(xindex.start())
并参考@QuantumMecha 的回答以了解原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.