Home > front end >  How to extract a specific string out of a list dependant on it's content
How to extract a specific string out of a list dependant on it's content

Time:09-14

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:

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!

CodePudding user response:

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)
  • Related