按lis中匹配的任何第一项拆分文本

2024-10-02 02:42:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种优雅的方法,从文本中的介词列表中找到第一个匹配项,这样我就可以解析一个文本,比如“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

Tags: ofthekeytextinmytablekeys
1条回答
网友
1楼 · 发布于 2024-10-02 02:42:36

您可以使用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个拆分,并连接最后两个部分:介词和字符串的其余部分

相关问题 更多 >

    热门问题