Python. 替换HTML标签之间的文本
我想写一个函数,用来高亮显示一些文本。这个函数接收一个HTML字符串作为输入,然后返回一个带有额外HTML标签的字符串。
举个例子:
输入字符串(需要高亮的词是“text”):
<div>
<a href="..." title="text to highlight">Some text to highlight</a>
<a href="..." title="text to highlight">Some other text to highlight</a>
</div>
输出字符串:
<div>
<a href="..." title="text to highlight">Some <b class="highlight">text</b> to highlight</a>
<a href="..." title="text to highlight">Some other <b class="highlight">text</b> to highlight</a>
</div>
我找到了一种正则表达式,可以匹配HTML标签之间的文本,但我不知道怎么在其中的某部分加上额外的标签。
highlight_str = u'text'
p = re.compile(r"[^<>]+(?=[<])")
iterator = p.finditer(search_str)
for match in iterator:
# code for replacement here ???
有没有其他的想法可以做到这一点呢?