如何在python中替换其他两个子字符串之间的子字符串?

2024-10-01 17:33:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

以上述为例,我将如何使用“the”作为起始子字符串,使用“intending”作为结束子字符串,除了删除它们之间存在的单词之外,还删除这两个单词,从而生成以下内容:

newSent = 'This is to edit'

Tags: theto字符串标记is文本文档thisam
2条回答

我会这样做:

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

希望这有帮助

您可以在此处使用regex替换:

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交叉的所有内容。这会阻止在the之前的一些intending上进行匹配,这是我们不想做的

相关问题 更多 >

    热门问题