Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract a specific string out of a list dependant on it's content

I have the following code to extract a "the content of a function" from a list:
This is the list:

funktionen = ['testfunction KL15 ein', '{', '$LIN::ZAS_Kl_15 = 1;', '}', '', 'testfunction Motor ein', '{', '$LIN::Motor_laeuft = 1;', '}', 'testfunction Warte_bis', '{', 'write("Warte bis");', '}']

The code:

line_stack = list(reversed(funktionen))  
content_funk = []
while len(line_stack) > 0:  # gebe Inhalt aus den Funktionen (innerhalb der {...}) aus
    next = line_stack.pop()
    if next == '{':
        scope_depth = scope_depth + 1
    elif next == '}':
        scope_depth = scope_depth - 1
    else:
    # test that we're inside at least one level of {...} nesting
        if scope_depth > 0:
            content_funk.append(next)

The result is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

content_funk = ['$LIN::ZAS_Kl_15 = 1;', '$LIN::Motor_laeuft = 1;', 'write("Warte bis");']

The problem is, that I only want the value of one "function"/value inside {}. So let’s say I have a variable function = Warte_bis as a input for the code above and the return value should be the content of testfunction Warte bis which in this case would be 'write("Warte bis");'. I hope it is clear what I mean. Thanks in advance!

>Solution :

if i understand correctly, you try to extract a function content depending on its name.

funktionen = ['testfunction KL15 ein', '{', '$LIN::ZAS_Kl_15 = 1;', '}', '', 'testfunction Motor ein', '{', '$LIN::Motor_laeuft = 1;', '}', 'testfunction Warte_bis', '{', 'write("Warte bis");', '}']
scope_depth = 0
line_stack = list(reversed(funktionen))  
content_funk = []
found = False
while len(line_stack) > 0:  # gebe Inhalt aus den Funktionen (innerhalb der {...}) aus
    next = line_stack.pop()
    if "Warte_bis" in next:
        found = True
    if next == '{':
        scope_depth = scope_depth + 1
    elif next == '}':
        scope_depth = scope_depth - 1
    else:
    # test that we're inside at least one level of {...} nesting
        if scope_depth > 0 and found:
            content_funk = next
            found = False
print(content_funk)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading