如何使用生成器(yield)递归查找几何模型层级结构?
递归查找几何模型文件的依赖子对象
问题背景
我们有一个包含链式关联对象的几何模型文件mymodel.txt,目标是通过层级关联名称或继承类,找出父对象(如surfname1)的所有依赖子对象。注意所有对象均以分号;结尾。
模型文件示例
[mymodel.txt]... FramePoint pointname0 * / 0.0 0.000 0.000 ; FramePoint pointname1 * / 1.0 0.000 0.000 ; FramePoint pointname2 * / 10.0 0.000 10.000 ; FramePoint pointname3 * / 10.0 10.000 10.000 ; FramePoint pointname4 * / 10.0 10.000 10.000 ; # ... FramePoint pointnameX * / 0.0 0.000 0.000 ; # ... CCurve curvename1 / pointname1 pointname2 pointname3 pointname4 ; IntBead bead1 / curvename1 *Z=0 pointname0 ; BSubCurve curvename2 / pointname0 ; # BSubCurve ... CLoftSurf surfname1 / curvename1 curvename2 ; # ...
现有Python代码
import os import logging import pathlib import re def findstr_in_file(str2find:str, inpfile, pattern:str='', G_line=None): G_line += G_line if G_line else '' file_path = pathlib.Path(inpfile) try: with file_path.open(mode="r") as file: for l_no, line in enumerate(file): for match in re.finditer(pattern + str2find, line): # 排除包含三个连续数值的行(如1.0002 2.0005 4.0009) if not re.findall('[0-9]+\.[0-9]+ +[0-9]+\.[0-9]+ +[0-9]+\.[0-9]+ +', line[line.rfind('/') + 1:]): print(f'Line Number:{l_no}; Line:{line}') # 拼接后续行直到找到结束标记; while not ';' in line: line += next(file) yield line # 提取/后的关联对象名称 obj_names = re.findall(r'\b[^\*|=]\w+\b', line[line.rfind('/') + 1:]) for objname in obj_names: if objname: findstr_in_file(objname, inpfile, pattern, G_line) break else: yield line break except OSError as error: logging.error(f'Reading file {file_path} failed due to: {error}') # 对象定义规则:ObjectType ObjectName + 规格说明 # 因此搜索模式为\w+ 空格 \w+ G_line = '' findstr_in_file('surfname1', 'mymodel.txt', '(\w+ +)', G_line)
需求说明
需实现使用**生成器(yield)**递归查找模型层级结构的功能。
内容的提问来源于stack exchange,提问作者MathArt
相关产品推荐
相关产品推荐

