【发布时间】:2020-07-18 06:05:18
【问题描述】:
我正在尝试找到一种仅根据给定单词拆分字符串的方法。
此外,新列表应尊重初始字符串(文本)的词序
以下几个例子:
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 ""
【问题讨论】:
-
如果单词是这样的:
hello、he和lo、loan、hell和and,输入是loandbeholdhellolo之类的呢? -
对于这种情况,取决于给定的单词顺序,例如应该首先以hello > hell > he)
-
我正在考虑首先获取单词的所有位置并将其存储并将它们从字符串中删除,直到我的单词列表完成。所以我可以重用子字符串的位置来在我的新列表中重新创建顺序。
标签: python regex string list split