Search code examples
pythoncadstep

Python - using regex to search for a string then append each match to a new list


I am currently trying to extract some data from a file which has this kind of format:

#12 = ADVANCED_FACE ( 'NONE', ( #194 ), #326, .F. ) ;
...
#159 = EDGE_LOOP ( 'NONE', ( #21, #124, #264, #145 ) ) ;
...
#194 = FACE_OUTER_BOUND ( 'NONE', #159, .T. ) ;
...
#326 = PLANE ( 'NONE',  #352 ) ;

The following is the method I am currently using:

faces_txt = re.findall(r'#(\d+) = ADVANCED_FACE.*;', text)

    faces = [int(face) for face in faces_txt]
    print('Face IDs = ', faces)

Which outputs:

Face IDs =  [12, 73, 99, 131, 181, 214, 244, 273, 330, 358]

What would I do if I wanted to create a new list (named sequentially like "Face1, Face2, Face3...") for each match of the "ADVANCED_FACE" rather than appending all of these values to the same list?


Solution

  • Without having more details on exact output you want and maybe some more input, it sounds like you want a list of lists or a dictionary of lists.

    faces_txt = re.findall(r'#(\d+) = ADVANCED_FACE.*;', text)
    faces = [int(face) for face in faces_txt]
    
    print('Face IDs = ', faces)
    
    LoL = []
    DoL = {}
    for i, faceId in enumerate(faces):
        LoL.append([faceId])
        DoL.update({"Face{}".format(i): [faceId]})
    
    print(LoL)
    print(DoL)
    
    print(DoL['Face0'])