python - 用 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>
解决方案
推荐阅读
- github - 从 SVN 连接到 GitHub 时出错
- powershell - 如何从 powershell 创建 IIS 网站以托管 .net core 2.0 应用程序
- python - 在列表中映射字典键值
- elasticsearch - 弹性搜索中的多级嵌套对象与“多个嵌套对象”
- java - 在 Junit5/gradle 项目中创建没有主类的 Jar 文件
- lua - 配置:错误:找不到 lua-libs
- twilio - 我可以使用相同的 twilio 号码连接多个自由职业者-客户对吗?
- c# - C#:如何避免多个选中的 RadioButtons
- java - Java.lang.NumberFormatException 错误:空字符串 - 汇率应用程序
- c++ - 尝试引用已删除的函数 UnitTest