'Parse txt file and save in python variable

I have a txt file containing following lines

term accept_1  
protocol:: tcp 
destination-port:: 24  


term accept_2  
protocol:: tcp 
source-port:: 21  
source-port-port:: 22  

What I am trying to do is the following: for each term, save the protocol in one variable, and the ports too (probably in an array).

I end up my research with PLY (Python Lex-Yacc), but I found it overcomplicated for my needs.

My actual code:

with fileinput.FileInput(file_pol,inplace = True, backup ='.bak') as policy:
        for line in policy:
            if "destination-port::" in line:
                extract_port = re.findall("\d+",line)
            elif  "source-port::" in line:
                extract_port = re.findall("\d+",line) 

The above is basically working but I miss the relation between term, protocol, port.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source