首页 > 解决方案 > 用 BS 美化的 Python 正则表达式替换缩进 HTML 的问题

问题描述

我正在尝试更改从 Beautiful Soup 的美化返回的 html 的缩进:

import re

def prettify_with_indent(prettified_str, indent_width=4):
   # continuous whitespace starting from a new line
   r = re.compile(r'^(\s*)', re.MULTILINE)

   # \1 is first capturing group, i.e. all continuous whitespace starting from a newline. 
   # replace whitespace from standard prettify with proper indents
   return r.sub(r'\1' * indent_width, prettified_str)

这适用于紧凑的 HTML,没有任何额外的换行符。但是,一旦出现额外的换行符,它就会成倍增加。我怎样才能防止这种情况?

prettified_str = r"""<p>
 some text
</p>
"""

print(indent(prettified_str))

结果:

<p>
    some text
</p>

乘以换行符的示例:

prettified_str_extra_newlines = r"""<p>
 some text

</p>
"""

print(indent(prettified_str_extra_newlines))

结果:

<p>
    some text




</p>

标签: pythonregexbeautifulsoup

解决方案


推荐阅读