【问题标题】:Replace word between two substrings (keeping other words)替换两个子字符串之间的单词(保留其他单词)
【发布时间】:2016-11-24 19:59:09
【问题描述】:

如果某个单词(例如on)位于两个子字符串之间(例如<temp></temp>),我正在尝试替换它,但是存在其他需要保留的单词。

string = "<temp>The sale happened on February 22nd</temp>"

替换后所需的字符串是:

Result = <temp>The sale happened {replace} February 22nd</temp>

我尝试过使用正则表达式,但我只能弄清楚如何替换位于两个 &lt;temp&gt; 标记之间的所有内容。 (因为.*?

result  = re.sub('<temp>.*?</temp>', '{replace}', string, flags=re.DOTALL)

但是on 可能会出现在字符串后面而不是&lt;temp&gt;&lt;/temp&gt; 之间,我不想替换它。

【问题讨论】:

标签: python regex


【解决方案1】:
re.sub('(<temp>.*?) on (.*?</temp>)', lambda x: x.group(1)+" <replace> "+x.group(2), string, flags=re.DOTALL)

输出:

<temp>The sale happened <replace> February 22nd</temp>

编辑:

根据 Wiktor 和 HolyDanna 的建议更改了正则表达式。

P.S:Wiktor 对这个问题的评论提供了一个更好的解决方案。

【讨论】:

  • 正则表达式其实不合适,思路是对的。
  • @WiktorStribiżew,谢谢。你能详细说明一下吗?如果您建议正确的正则表达式,我将替换它,否则如果您要回答这个问题,那么我将根据您的答案删除我的答案。
  • 这行得通,但是是否可以将其限制在 之间?如果它在标签之外,也会替换它
  • 一两句话:这个正则表达式('(&lt;temp&gt;.*?)on(.*?&lt;/temp&gt;)')将删除&lt;temp&gt;....&lt;/temp&gt;字符串中的1个on子字符串,2)on将像这样被删除 - &lt;temp&gt;The sale postponed on February 22nd&lt;/temp&gt; - >&lt;temp&gt;The sale postp&lt;replace&gt;ed on February 22nd&lt;/temp&gt;。我猜你想要rr'(&lt;temp&gt;.*?) on (.*?&lt;/temp&gt;)' 并替换为x.group(1)+" &lt;replace&gt; "+x.group(2),3)这不考虑嵌套的&lt;temp&gt; 标签。
  • 这可能会失败,如果在一行中有多个临时构造,在中间(但不在一个内)。我还建议在 on 周围使用单词边界。
【解决方案2】:

试试lxml:

from lxml import etree

root = etree.fromstring("<temp>The sale happened on February 22nd</temp>")
root.text = root.text.replace(" on ", " {replace} ")
print(etree.tostring(root, pretty_print=True))

输出:

<temp>The sale happened {replace} February 22nd</temp>

【讨论】:

  • 我认为您需要有代码才能找到 &lt;temp 标签,因为它们可能是某个较大文件的一部分。
  • string 是有效的 XML。让我们把问题写下来,不要让我们猜测。
猜你喜欢
  • 2019-10-27
  • 2015-11-21
  • 1970-01-01
  • 1970-01-01
  • 2014-04-29
  • 2015-04-08
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
相关资源
最近更新 更多