使用python正则表达式替换HTML片段中的块

2024-10-01 02:35:40 发布

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

给定文本中的通用HTML代码段,是否有任何方法可以将块1替换为块2:

  1. <br /> Text2 <br />
  2. <p> Text2 </p>

到目前为止,这是我使用python和正则表达式所能做到的

text =  '<p>Text1</p> <br/ >Text2 <br /> <p> </p> <br/>'
pattern = "<br />(?!<p>|</p>)<br />"
matches = [ match for match in re.finditer(pattern, text) ]
#matches = [ '<p>Text1</p> <br/ >Text2 <br /> <p> </p> <br/>' ]

它匹配整个文本,但我只对一次替换(一行)感兴趣。这是一种很好的方法吗?或者您更喜欢捕获其中的内容,即“Text2”并在所需的最终文本中插入<p> </p>块的内部

final_text = '<p>Text1</p> <p>Text2 </p> <p> </p> <br/>'

Tags: 方法textin文本brreforhtml
1条回答
网友
1楼 · 发布于 2024-10-01 02:35:40

下面的例子是给你一个想法,你可以自己实现

from simplified_scrapy.core.regex_helper import replaceReg,regSearch
html = '''
<p>Text1</p> <br />Text2 <br /> <p> </p> <br/>
<p>Text11</p> <br />Text12 <br /> <p> </p> <br/>
'''
while True: # Use cycle to process one by one
    o = regSearch(html,"<br\s*/>[^<]*<br\s*/>") # Take out the data to be replaced
    if not o: break
    n = replaceReg(o,"<br\s*/>","<p>",1) # Replace start
    n = replaceReg(n,"<br\s*/>","</p>",1) # Replace end
    html = html.replace(o,n)
print (html)

结果:

<p>Text1</p> <p>Text2 </p> <p> </p> <br/>
<p>Text11</p> <p>Text12 </p> <p> </p> <br/>

相关问题 更多 >