【问题标题】:How to replace substring between two other substrings in python?如何在python中替换其他两个子字符串之间的子字符串?
【发布时间】:2019-10-30 15:56:20
【问题描述】:

我有一个文本文档语料库,其中一些会有一个子字符串序列。第一个和最后一个子串是一致的,并标记了我要替换的部分的开始和结束。但是,我还想删除/替换这些第一个和最后一个位置之间存在的所有子字符串。

origSent = 'This is the sentence I am intending to edit'

以上面为例,我将如何使用'the'作为开始子字符串,'intending'作为结束子字符串,除了它们之间存在的单词之外,删除它们以进行以下操作:

newSent = 'This is to edit'

【问题讨论】:

  • 你需要更清楚地定义这些子字符串的规则,如果'the'和'intending'总是定义词,那么通过str.split()当然是微不足道的

标签: python string


【解决方案1】:

您可以在这里使用正则表达式替换:

origSent = 'This is the sentence I am intending to edit'
newSent = re.sub(r'\bthe((?!\bthe\b).)*\bintending\b', '', origSent)
print(newSent)

打印出来:

This is  to edit

正则表达式模式中的“秘诀”是回火点:

((?!\bthe\b).)*

这将消耗所有跨越另一个单词the的内容。这可以防止在intending 之前匹配一些较早的the,这是我们不想做的。

【讨论】:

    【解决方案2】:

    我会这样做:

    s_list = origSent.split()
    newSent = ' '.join(s_list[:s_list.index('the')] + s_list[s_list.index('intending')+1:])
    

    希望这会有所帮助。

    【讨论】:

    • 我认为您错过了第二行中的 = 符号。它应该说“newSent = ' '.join ...”
    • 更正了答案
    猜你喜欢
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2016-11-24
    • 2019-11-21
    相关资源
    最近更新 更多