簡體   English   中英

根據列表中的給定單詞拆分字符串

[英]Split string based on given words from list

我正在嘗試找到一種僅根據給定單詞拆分字符串的方法。

新列表也應該尊重初始字符串(文本)的詞序

下面的幾個例子:

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 個示例,function 應返回:

["hello", "world", "hello"]
["hello", "worldhowareyou", "hello"]
["hello", "world", "how", "are", "you", "hello"]

我不知道該怎么做(我嘗試了諸如 split 之類的功能,但到目前為止沒有任何效果。

我知道如何創建自己的算法,但我想知道是否有任何內置函數可以用於這種情況。

先感謝您。

編輯:

到目前為止,我能夠檢測到我所有的單詞出現 / position / 字長

保持單詞和切片字符串的順序可能非常有用。

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 ""

對於建議的示例, 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']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM