Python中用regex替换嵌套字符串

2024-06-16 08:32:55 发布

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

我有一堆HTML页面,在这些页面中我想将CSS格式的文本片段转换成标准的HTML标记。e、 g<span class="bold">some text</span>将变成{}

我被困在嵌套的span片段:

<span class="italic"><span class="bold">XXXXXXXX</span></span>
<span class="italic">some text<span class="bold">nested text<span class="underline">deep nested text</span></span></span>

我想用Python的regex库转换片段。正则表达式搜索-替换上述输入的最佳策略是什么?在


Tags: text标记文本标准html格式some页面
1条回答
网友
1楼 · 发布于 2024-06-16 08:32:55

我的解决方案使用lxml和cssselect以及一些Python:

#!/usr/bin/env python

import cssselect  # noqa
from lxml.html import fromstring


html = """
<span class="italic"><span class="bold">XXXXXXXX</span></span>
<span class="italic">some text<span class="bold">nested text<span class="underline">deep nested text</span></span></span>
"""

class_to_style = {
    "underline": "u",
    "italic": "i",
    "bold": "b",
}

output = []
doc = fromstring(html)
spans = doc.cssselect("span")
for span in spans:
    if span.attrib.get("class"):
        output.append("<{0}>{1}</{0}>".format(class_to_style[span.attrib["class"]], span.text or ""))
print "".join(output)

输出:

^{pr2}$

NB:这是一个幼稚的解决方案,不能产生正确的输出,因为您必须保留一个打开的标签队列,并在最后关闭它们。在

相关问题 更多 >