【问题标题】:Python - search for string, extract number from line and append to listPython - 搜索字符串,从行中提取数字并附加到列表
【发布时间】:2018-05-24 09:24:11
【问题描述】:

我正在使用一种 STEP 文件格式,我想对其进行解析、提取信息并将其存储在数组中,以便稍后在程序中调用并对它们执行数学运算。

以下是我正在处理的数据示例(advanced_face 稍后在数据文件中引用 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

我将如何去除正则表达式匹配,以便仅将数字附加到列表中?

【问题讨论】:

    标签: python cad step


    【解决方案1】:

    您可以在正则表达式中使用组,并在附加到面孔列表之前将字符串“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))
    

    【讨论】:

    • 感谢您的快速回复。工作完美。只是为了让我明白它来自哪里,为什么组号是 1?
    • 由于文件格式是分层的,我认为这可能是为每个人脸创建列表的更好方法。因此,搜索 ADVANCED_FACE 的第一个匹配项,附加 ID.. 然后搜索该面的 FACE_OUTER_BOUND,附加 ID.. 等等,直到我有一个定义每个面的列表。知道我会怎么做吗?
    • group(1) 表示从 () 中的正则表达式获取组,如果我们有 re.findall('#(\d) = ADVANCED_FACE (.*);'),组 0 就是所有正则表达式0) 是所有文本 group(1) 是 (\d) group(2) 是字符串 ('NONE', (#194), #326, .F.) 在这种情况下,为了得到所有的脸,在我看来这是个好方法将是faces_txt = re.findall(r'#(\d+) = (.*)(.*;', text) # return list of couples group(1), group(2) use ( as feature to end of face name faces = [int(face), face_name for face_id, face_name in faces_txt]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2011-09-27
    • 1970-01-01
    相关资源
    最近更新 更多