你可以用
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')
(in|on|under)
. 请注意括号:它们允许我们捕获拆分字符串的字符串,以便将它们保留在输出中。
然后,我们拆分,最多允许1个拆分,并连接最后两个部分:介词和字符串的其余部分。