我正在寻找一种优雅的方法,从文本中的介词列表中找到第一个匹配项,这样我就可以解析一个文本,比如“Add shoes behind the window”,结果应该是[“shoes”,“behind the window”]
只要课文中没有多个介词,它就能起作用
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
在第二个例子中,结果应该是[“我的钥匙”,“厨房桌子下面”]
找到列表中任何单词的第一个匹配项的优雅方法是什么
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
您可以使用re.split执行此操作:
首先,我们创建一个看起来像
(in|on|under)
的正则表达式。请注意括号:它们允许我们捕获拆分字符串的字符串,以便将它们保留在输出中然后,我们拆分,最多允许1个拆分,并连接最后两个部分:介词和字符串的其余部分
相关问题 更多 >
编程相关推荐