【问题标题】:Best way to split a string in python with multiple separators - while keeping the separators在 python 中使用多个分隔符拆分字符串的最佳方法-同时保留分隔符
【发布时间】:2019-10-02 13:59:52
【问题描述】:

假设我有字符串:

string = "this is a test string <LW> I want to <NL>split this string<NL> by each tag I have inserted.<AB>"

我想通过在前一个函数中插入字符串中的每个自定义标签来拆分字符串:

tags = ["<LW>", "<NL>", "<AB>"]

这是所需的输出:

splitString = splitByTags(string, tags)

for s in splitString:
    print(s)

输出

"this is a test string <LW>"
" I want to <NL>"
"split this string<NL>"
" by each tag I have inserted.<AB>"

所以基本上我想将字符串拆分为多个子字符串,同时将这些子字符串保留在拆分中。最快和最有效的方法是什么?我知道我可以使用 string.split 并简单地将拆分文本附加到每一行,但是我不确定如何使用多个字符串来执行此操作。

【问题讨论】:

标签: python regex string split substring


【解决方案1】:

这里有一些如何做到这一点的例子:

import re

def split_string(string, tags):
    string_list = []
    start = 0
    for tag in tags:
        tag_index = re.finditer(tag, string)
        for item in tag_index:
            end_tag = item.start() + len(tag)
            string_list.append(string[start:end_tag])
            start = end_tag

    return string_list



data = split_string(string, tags)

输出:

['this is a test string <LW>', ' I want to <NL>', 'split this string<NL>', ' by each tag I have inserted.<AB>']

【讨论】:

    【解决方案2】:

    re.split 与捕获括号一起使用。

    例如:

    import re
    string = "this is a test string <LW> I want to <NL>split this string<NL> by each tag I have inserted.<AB>"
    tags = ["<LW>", "<NL>", "<AB>"]
    
    splt_str = re.split("(" + "|".join(tags) + ")", string)
    
    for i in range(0, len(splt_str), 2):
        print("".join(splt_str[i:i+2]))
    

    输出:

    this is a test string <LW>
     I want to <NL>
    split this string<NL>
     by each tag I have inserted.<AB>
    

    【讨论】:

    • documentation of re.split中的这句话解释:“如果在模式中使用捕获括号,那么模式中所有组的文本也作为结果列表的一部分返回”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多