Python 根据列表中的给定单词拆分字符串

Python 根据列表中的给定单词拆分字符串,python,regex,string,list,split,Python,Regex,String,List,Split,我正试图找到一种只基于给定单词分割字符串的方法 此外,新列表应遵循初始字符串(文本)的词序 以下几个例子: def split_str_from_words(words, text): return ??? split_str_from_words(["hello", "world"], "helloworldhello") split_str_from_words(["hello"], "helloworldhowareyouhello") split_str_from_words(

我正试图找到一种只基于给定单词分割字符串的方法

此外,新列表应遵循初始字符串(文本)的词序

以下几个例子:

def split_str_from_words(words, text):
    return ???

split_str_from_words(["hello", "world"], "helloworldhello")
split_str_from_words(["hello"], "helloworldhowareyouhello")
split_str_from_words(["hello", "how", "are", "you", "world"], "helloworldhowareyouhello")
根据上述3个示例,函数应返回:

["hello", "world", "hello"]
["hello", "worldhowareyou", "hello"]
["hello", "world", "how", "are", "you", "hello"]
我不知道该怎么做(我试过使用split之类的函数,但到目前为止都没有达到预期效果)

我知道如何创建自己的算法,但我想知道是否有任何内置函数可用于此情况

先谢谢你

编辑:

到目前为止,我能够检测到我所有的单词出现/位置/单词 长度

保持单词的顺序和切片字符串可能非常有用

import re

def split_str_from_words(words, text):
    for word in words:
        positions = [m.start() for m in re.finditer(word, text)]
        print(word, positions, len(positions), len(word))

    return ""
对于建议的示例,将所有要与
|
匹配的单词连接起来应该可以

def split_str_from_words(l, s):
    m = re.split(rf"({'|'.join(l)})", s)
    return [i for i in m if i] # removes empty strings (improvements are welcome)


如果单词是这样的:
hello
he
lo
loan
hell
并且输入是
loand beholdhellolo
之类的东西呢?对于这种情况,它将取决于给定的单词顺序,例如应该首先以hello>hell>he开头)我想首先获取单词的所有位置并存储它,然后将它们从字符串中删除,直到我的单词列表完成。因此,我可以重复使用子字符串的位置来重新创建我的新列表中的顺序。这是完美的工作,非常聪明地使用re.split它也尊重顺序(如果我输入hello,hell或hell,hello将影响结果)非常感谢!!
import re

split_str_from_words(["hello", "world"], "helloworldhello")
# ['hello', 'world', 'hello']

split_str_from_words(["hello"], "helloworldhowareyouhello")
# ['hello', 'worldhowareyou', 'hello']

split_str_from_words(["hello", "how", "are", "you", "world"], "helloworldhowareyouhello")
# ['hello', 'world', 'how', 'are', 'you', 'hello']