【问题标题】:Split string based on given words from list根据列表中的给定单词拆分字符串
【发布时间】: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 ""

【问题讨论】:

  • 如果单词是这样的:helloheloloanhelland,输入是 loandbeholdhellolo 之类的呢?
  • 对于这种情况,取决于给定的单词顺序,例如应该首先以hello > hell > he)
  • 我正在考虑首先获取单词的所有位置并将其存储并将它们从字符串中删除,直到我的单词列表完成。所以我可以重用子字符串的位置来在我的新列表中重新创建顺序。

标签: python regex string list split


【解决方案1】:

对于建议的示例,re.split 加入所有要与| 匹配的单词应该可以。

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)

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']

【讨论】:

  • 这工作很完美,re.split 的使用非常聪明。它也尊重顺序(如果我输入hello,hell 或hell,hello 会影响结果)非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-05-26
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 2017-08-16
  • 2011-01-16
  • 2013-06-26
相关资源
最近更新 更多