dimanche 30 août 2020

Is there a more concise way to returning words in a specified text with a combination of characters

I need to create a function that accepts a block of text as an argument, then matches and returns any word containing at least one of the strings/combination of characters below:

- tion (as in navigation, isolation, or mitigation)
- ex (as in explanation, exfiltrate, or expert)
- ph (as in philosophy, philanthropy, or ephemera)
- ost, ist, ast (as in hostel, distribute, past)

I have used a for loop to search for and append these patterns to a list:

def f(string):
    string_list = string.split()
    match_list = []
    for word in string_list:
        if "tion" in word:
            match_list.append(word)
        if "ex" in word:
            match_list.append(word)
        if "pht" in word:
            match_list.append(word)
        if "ost" in word:
            match_list.append(word)
        if "ist" in word:
            match_list.append(word)
        if "ast" in word:
            match_list.append(word)
    return match_list

print (f(text))

How could I write this code more efficiently?

Aucun commentaire:

Enregistrer un commentaire