我正在使用我想解析的步骤文件格式,提取信息并将其存储在阵列中,以便我可以在程序稍后在程序中呼叫并执行数学操作。p>下面是我正在使用的数据的一个示例(advedical_face coutences face_outer_bound稍后在数据文件中:
#12 = ADVANCED_FACE ( 'NONE', ( #194 ), #326, .F. ) ;
...
#194 = FACE_OUTER_BOUND ( 'NONE', #159, .T. ) ;
这是我到目前为止提出的:
import re
with open('TestSlot.STEP', 'r') as step_file:
data = step_file.readlines()
NF = 0
faces = []
for line in data:
line = line.strip()
if re.search("ADVANCED_FACE", line):
NF = NF + 1
advface = re.compile('#d+')
advfaceresult = advface.match(line)
faces.append(advfaceresult.group())
print("Face IDs =", faces)
print("Number of faces, NF =", NF)
这给出了输出:
Face IDs = ['#12', '#73', '#99', '#131', '#181', '#214', '#244',
'#273', '#330', '#358']
Number of faces, NF = 10
我将如何剥离正则匹配匹配,因此只有该数字就附加到列表中?
您可以在Regex中使用组,然后将字符串'12'转换为编号12,然后再添加到面部列表 advface = re.compile('#(d+)')
advfaceresult = advface.match(line)
faces.append(int(advfaceresult.group(1)))
结果将是face ids = [12,...]
也可以通过
达到解决方案import re
ifile = r'TestSlot.STEP'
with open(ifile) as f:
text = f.read() # read all text
faces_txt = re.findall(r'#(d+) = ADVANCED_FACE.*;', text)
# get all groups by re
faces = [int(face) for face in faces_txt] # convert to int
print('Face IDs = ', faces)
print('Number of faces, NF =', len(faces))