要读取STL ASCII格式的文件,可以使用Python的文件操作和文本解析库来实现。下面是一个示例代码,演示了如何读取并解析STL ASCII格式文件的方法:
import re
def read_stl_file(file_path):
vertices = []
normals = []
with open(file_path, 'r') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
if line.startswith('facet normal'):
normal = re.findall(r'[-+]?\d*\.\d+|\d+', line)
normals.append([float(normal[0]), float(normal[1]), float(normal[2])])
elif line.startswith('vertex'):
vertex = re.findall(r'[-+]?\d*\.\d+|\d+', line)
vertices.append([float(vertex[0]), float(vertex[1]), float(vertex[2])])
return vertices, normals
# 读取STL文件
file_path = 'path_to_stl_file.stl'
vertices, normals = read_stl_file(file_path)
# 输出顶点和法线信息
for i in range(len(vertices)):
print('Vertex {}: {}'.format(i+1, vertices[i]))
print('Normal {}: {}'.format(i+1, normals[i]))
请注意,此示例代码假设STL文件的格式正确,并且每个facet都有3个顶点和一个法线。如果STL文件的格式与此不同,可能需要适当修改代码。此外,还可以根据需要扩展代码以支持其他STL文件的功能。