split text by any first item matched from a list

Viewed 68

I am looking for an elegant way to find the first match from a list of prepositions in a text so that I can parse a text like "Add shoes behind the window", the result should be ["shoes","behind the window"]

It works as long as there are not multiple prepositions in the text

my keys behind the window before: my keys after: behind the window

my keys under the table in the kitchen before: my keys under the table after: in the kitchen

my keys in the box under the table in the kitchen before: my keys after: in the box under the table in the kitchen

In the 2nd example, the result should be ["my keys","under the table in the kitchen"]

Whats an elegant way to find the first match of any of the words in the list?

def get_text_after_preposition_of_place(text):
    """Returns the texts before[0] and after[1] <preposition of place>"""

prepositions_of_place = ["in front of","behind","in","on","under","near","next to","between","below","above","close to","beside"]
    textres = ["",""]

    for key in prepositions_of_place:
        if textres[0] == "":
            if key in text:
                textres[0] = text.split(key, 1)[0].strip()
                textres[1] = key + " " + text.split(key, 1)[1].strip()
    return textres
1 Answers

You can do that using re.split:

import re

def get_text_after_preposition_of_place(text):
    """Returns the texts before[0] and after[1] <preposition of place>"""

    prepositions_of_place = ["in front of","behind","in","on","under","near","next to","between","below","above","close to","beside"]
     preps_re = re.compile(r'\b(' + '|'.join(prepositions_of_place) + r')\b')

    split = preps_re.split(text, maxsplit=1)
    return split[0], split[1]+split[2]

print(get_text_after_preposition_of_place('The cat in the box on the table'))  
# ('The cat ', 'in the box on the table')

First, we create a regex that will look like (in|on|under). Note the parentheses: they will allow us to capture the strings on which we split the string in order to keep them in the output.

Then, we split, allowing 1 split at most, and concatenate the last two parts: the preposition and the rest of the string.

Related