'Python - if ... then with multiple wildcards

I use the following python snippet within my code to scan a given soup for keywords. It´s only possible that one of the word is inside the soup. Concerning to the result the code do different things. In my first version, there was only one keyword. If it is in the soup, i did the one thing, if not, the code did another thing. While working with my programm, i added more keywords and more routes my code can go concering to the keyword. And here things are getting complicated...:

    section = soup.findAll(text="SEARCH_WORD_A")
    #print(section)
    if not section:
        section2 = soup.findAll(text="SEARCH_WORD_B")
        if not section2:
            print("Found Nothing")
        if section2:
            print("Found_SEARCH_WORD_B")
    if section:
        print("SEARCH_WORD_A")

I will have a lot more keywords in the future and want to get some easier code... some better code. It should work like that:

Scan soup for given keywords If WORD_A is found: do that IF WORD_B: do something else IF WORD_C: do another thing If nothing found: print some stuff...

As i mentioned, in the soup there could only one keyword be found.



Solution 1:[1]

Try something like this:

section_names = ["SEARCH_WORD_A", "SEARCH_WORD_B", "SEARCH_WORD_C"]
found_any = False

for section_name in section_names:
    section = soup.findAll(text=section_name)
    if section:
        print("Found_" + section_name)
        found_any = True

if not found_any:
    print("Found Nothing")

This works by taking a list of section names, and looping through them. For each section it checks if it is in the soup, and if it is, it prints it and sets the variable found_any to True. Any code you want for each section can then be executed here. Then, once it has finished the loop, it checks whether any were found, and if not, you can execute some code.

Alternatively, if you want to execute different code for each section, you could just use if, elif and else:

    if soup.findAll(text="SEARCH_WORD_A"):
        print("Found_A")
    elif soup.findAll(text="SEARCH_WORD_B"):
        print("Found_B")
    elif soup.findAll(text="SEARCH_WORD_C"):
        print("Found_C")
    else:
        print("Found Nothing")

Pro tip, if you are wanting to then use the section variable if it is found, and you're using a recent python version, you can use the walrus operator := to assign to a variable directly in the conditional line:

if section := soup.findAll(text="SEARCH_WORD_A"):
    print("Found_A")
    print(section)  # This is using the variable assigned in the if statement using :=

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Strike Digital