Python 如何迭代多个正则表达式匹配并替换它们?

Python 如何迭代多个正则表达式匹配并替换它们?,python,html,regex,Python,Html,Regex,将包含单词fear的每个句子替换为相同的句子,用class=“fear”将其包装在b标签中。 尝试将此模式的每个匹配项(总共2个)包装为html标记 import re with open('chicken.txt', 'r') as file: pattern = re.compile(r'[^\.]+fear[^\.]+') text = file.read() matches = pattern.finditer(text) tagstart = '<b class="fe

将包含单词fear的每个句子替换为相同的句子,用class=“fear”将其包装在b标签中。

尝试将此模式的每个匹配项(总共2个)包装为html标记

import re
with open('chicken.txt', 'r') as file:
pattern = re.compile(r'[^\.]+fear[^\.]+')
text = file.read()
matches = pattern.finditer(text)
tagstart = '<b class="fear">'
tagend = '</b>'

replacement = [text.replace(match[0], tagstart + match[0] + tagend) for match in matches]

with open('chick.html', 'w') as htmlfile:
    htmlfile.write(replacement[0])
重新导入
以open('chicken.txt','r')作为文件:
模式=重新编译(r'[^\.]+恐惧[^\.]+')
text=file.read()
matches=pattern.finditer(文本)
标记开始=“”
tagend=''
替换=[text.replace(匹配[0],tagstart+match[0]+tagend)用于匹配中的匹配]
将open('chick.html','w')作为htmlfile:
htmlfile.write(替换[0])
chick.html输出如下所示:

If you've spent much time with chickens, you may doubt their ability to process a thought as complex as
"Chicken A will beat me anyway, so why bother to fight?" Your doubt is well placed.
Pecking orders are yet another case where the "thinking" has been done by natural selection,
and so needn't be done by the organism.<b class="fear"> The organism must be able to tell its neighbors apart,
and to feel a healthy fear of the ones that have brutalized it, but it needn't grasp the logic behind the fear</b>.
Any genes endowing a chicken with this selective fear, reducing the time spent in futile and costly combat, should flourish.
如果你花了很多时间和鸡在一起,你可能会怀疑它们处理如此复杂思想的能力
“鸡A无论如何都会打我,那为什么还要费心打架呢?”你的怀疑是正确的。
啄食顺序是另一种“思考”是由自然选择完成的情况,
因此不需要由生物体来完成。这种生物必须能够区分它的邻居,
对那些残忍的人有一种健康的恐惧,但它不需要掌握恐惧背后的逻辑。
任何赋予鸡这种选择性恐惧、减少徒劳和昂贵战斗时间的基因,都应该蓬勃发展。

最后一句话是替换变量中的第二项,in不包含在b标记中。

您可以使用replace从
findinter
迭代每个
匹配项,但每次都对整个文本执行替换

重新导入
模式=重新编译(r'[^\.]+恐惧[^\.]+')
标记开始=“”
tagend=''
以open('chicken.txt','r')作为文件:
text=file.read()
matches=pattern.finditer(文本)
对于匹配中的匹配:
text=text.replace(匹配[0],标记开始+匹配[0]+标记结束)
将open('chick.html','w')作为htmlfile:
htmlfile.write(文本)
文件chick.html

如果你花了很多时间和鸡在一起,你可能会怀疑它们处理问题的能力
你的疑问是,就像“鸡A无论如何都会打我,那么为什么还要费事去打呢?”
位置很好。啄食顺序是另一种“思考”由自然完成的情况
选择,因此无需由生物体完成。有机体必须能够分辨
它的邻居分开了,并且对那些残暴的人感到健康的恐惧,但是
它不需要掌握恐惧背后的逻辑。任何基因赋予一只鸡
这种选择性的恐惧,减少了徒劳和昂贵的战斗所花费的时间,应该蓬勃发展。

请删除图像,改为包含样本输入和输出,两种格式均为文本。但其中包含html标记,无法正确格式化。如果将其格式化为代码,前面有四行,则效果会很好。泰姆!