Search code examples
pythonregextext-parsingbracketsopenfoam

Reading text file for specfic keyword included inside brackets '{'


I would like to read a text file which is like below. It has Geometry names --> " hvac,OUTLET,INLET,Lamelle,duct and wall"

In this case only 6, but I may vary depending on the different simulation of CFD process.

I would like to extract only the Geometry names and its corresponding 'type'. In my case the geometry and types are " hvac,OUTLET,INLET,Lamelle,duct and wall" and "wall and patch" respectively.

Should I use Parse using XML or just search for the string after '{\n' and '}\n' Keyword .

geometry
{
    hvac
    {
        type            wall;
        inGroups        1(wall);
        nFaces          904403;
        startFace       38432281;
    }
    OUTLET
    {
        type            patch;
        nFaces          8228;
        startFace       39336684;
    }
    INLET
    {
        type            patch;
        nFaces          347;
        startFace       39344912;
    }
    Lamelle
    {
        type            wall;
        inGroups        1(wall);
        nFaces          204538;
        startFace       39345259;
    }
    duct
    {
        type            wall;
        inGroups        1(wall);
        nFaces          535136;
        startFace       39549797;
    }
    wall
    {
        type            wall;
        inGroups        1(wall);
        nFaces          118659;
        startFace       40084933;
    }
}

Solution

  • The answer depends on whether you want to support the whole general OpenFOAM's dictionary format, or not.

    If you only need to support format similar to what you have shown in the question, then a simple regex like \b(\w+)\s+{\s+type\s+(\w+); would do: https://regex101.com/r/yV8tK2/1 . This can be your option if you fully control how this dictionary is created, though in that case it might be even simpler for you to obtain the needed information directly from the code that creates the dictionary.

    However, OpenFOAM's format for dictionaries is much more rich than your example. It can allow for #include directives, can allow for regexs as keys, can allow for referencing of other keys using $ syntax, can allow for comments, C++ code snippets and probably many more (I do not pretend to know it well). A typical example can be two dictionaries:

    ---- File data.incl:
    
    baseType wall;
    
    ---- File data
    
    #inputMode merge;
    #include "data.incl"
    
    geometry {
        /* foo {    
            type wrongType; // a commented entry
        } */ 
        foo {
            type $baseType; // this will expand to wall
            ...
        }
        "(bar|buz)" {  // this will match bar and buz
             ...
        } 
    }
    

    If you need to parse any such dictionary, then I strongly recommend you to code in C++ and use standard OpenFOAM classes, which will allow you to do this in just a couple of lines of code.