Python如何按特定位置逗号分割含HTML标签的字符串?
解决HTML标签间逗号分割问题
问题场景
原始字符串如下:
<div class="options mceEditable">The membrane is a dynamic structure, and its constituents are in constant movement.</div>, <div class="options mceEditable">The lipids component of the membrane constitutes a bilayer of hydrophilic ends</div>, <div class="options mceEditable">The lipid content of the membrane is more than that of the protein</div>, <div class="options mceEditable">The proteins may either be carriers or receptors only</div>, <div class="options mceEditable">It is a 3-layered lipid structure</div>
需求:仅分割</div>与<div>之间的逗号(即, <div这类位置的逗号),保留标签内的逗号,最终得到由完整<div>标签组成的列表,期望输出:
['<div class="options mceEditable">The membrane is a dynamic structure, and its constituents are in constant movement.</div>', '<div class="options mceEditable">The lipids component of the membrane constitutes a bilayer of hydrophilic ends</div>', '<div class="options mceEditable">The lipid content of the membrane is more than that of the protein</div>', '<div class="options mceEditable">The proteins may either be carriers or receptors only</div>', '<div class="options mceEditable">It is a 3-layered lipid structure</div>']
错误尝试分析
你之前的代码存在两个问题:
options = test3.split(">, <") options=options.replace("</div'","</div>'")
- 用
">, <"分割会直接截断标签结构,导致每个元素的首尾标签不完整; split()返回的是列表,列表没有replace()方法,这行代码会直接触发报错。
正确解决方案
使用正则表达式的零宽断言精准定位需要分割的逗号位置,确保只分割</div>之后、<div>之前的逗号(含空格):
import re test3 = '<div class="options mceEditable">The membrane is a dynamic structure, and its constituents are in constant movement.</div>, <div class="options mceEditable">The lipids component of the membrane constitutes a bilayer of hydrophilic ends</div>, <div class="options mceEditable">The lipid content of the membrane is more than that of the protein</div>, <div class="options mceEditable">The proteins may either be carriers or receptors only</div>, <div class="options mceEditable">It is a 3-layered lipid structure</div>' # 反向预查+正向预查定位分割点 options = re.split(r'(?<=</div>), (?=<div)', test3) print(options)
正则表达式说明:
(?<=</div>):反向预查,确保分割点前是完整的</div>标签;,:匹配需要分割的逗号和后续空格;(?=<div):正向预查,确保分割点后是<div标签起始部分。
分割后每个元素都是完整的<div>标签,同时保留了标签内的逗号,完全符合需求。
内容的提问来源于stack exchange,提问作者Shiva
相关产品推荐
相关产品推荐

