有什么方法可以为.prettify()
函数定义自定义缩进宽度吗?从我能从中得到的
def prettify(self, encoding=None, formatter="minimal"):
if encoding is None:
return self.decode(True, formatter=formatter)
else:
return self.encode(encoding, True, formatter=formatter)
无法指定缩进宽度。我认为是因为decode_contents()
函数中的这一行-
s.append(" " * (indent_level - 1))
固定长度为1个空格! (为什么!)我尝试指定indent_level=4
,这只会导致-
<section>
<article>
<h1>
</h1>
<p>
</p>
</article>
</section>
看起来很愚蠢。 😐
现在,我可以解决这个问题,但是我只想确定是否有任何我想念的东西。因为这应该是一个基本功能。 :-/
如果您有更好的美化HTML代码的方法,请告诉我。
参考方案
实际上,我本人以最骇人听闻的方式处理了这个问题:通过对结果进行后处理。
r = re.compile(r'^(\s*)', re.MULTILINE)
def prettify_2space(s, encoding=None, formatter="minimal"):
return r.sub(r'\1\1', s.prettify(encoding, formatter))
实际上,我在该类中使用了prettify_2space
代替了prettify
。这对于解决方案不是必需的,但是无论如何,还是让它做吧,并将缩进宽度作为参数,而不是将其硬编码为2:
orig_prettify = bs4.BeautifulSoup.prettify
r = re.compile(r'^(\s*)', re.MULTILINE)
def prettify(self, encoding=None, formatter="minimal", indent_width=4):
return r.sub(r'\1' * indent_width, orig_prettify(self, encoding, formatter))
bs4.BeautifulSoup.prettify = prettify
所以:
x = '''<section><article><h1></h1><p></p></article></section>'''
soup = bs4.BeautifulSoup(x)
print(soup.prettify(indent_width=3))
……给出:
<html>
<body>
<section>
<article>
<h1>
</h1>
<p>
</p>
</article>
</section>
</body>
</html>
显然,如果要修补Tag.prettify
和BeautifulSoup.prettify
,则必须在此处执行相同的操作。 (您可能想要创建一个可以应用于两者的通用包装器,而不是重复自己。)而且,如果还有其他prettify
方法,则可以相同。
我有以下Python代码编写项目的依赖文件。它可以在Python 2.x上正常工作,但是在使用Python 3进行测试时会报告错误。depend = None if not nmake: depend = open(".depend", "a") dependmak = open(".depend.mak…
Python Pandas导出数据 - python我正在使用python pandas处理一些数据。我已使用以下代码将数据导出到excel文件。writer = pd.ExcelWriter('Data.xlsx'); wrong_data.to_excel(writer,"Names which are wrong", index = False); writer.…
Python:对于长时间运行的进程,通过还是休眠? - python我正在编写一个队列处理应用程序,该应用程序使用线程等待和响应要发送到该应用程序的队列消息。对于应用程序的主要部分,只需要保持活动状态即可。对于像这样的代码示例:而True: 通过要么而True: time.sleep(1)哪一个对系统的影响最小?除了保持python应用运行外,什么都不做的首选方式是什么? 参考方案 我可以想象time.sleep()会减少系…
Python:无符号32位按位算术 - python试图回答另一篇有关其解决方案涉及IP地址和网络掩码的文章时,我陷入了普通的按位算法。在Python中,是否存在一种标准的方式来进行按位AND,OR,XOR,NOT运算,假设输入是“32位”(可能是负数)整数或long,并且结果必须是[[ 0,2 ** 32]?换句话说,我需要一个与无符号长整数之间的C按位运算有效的Python对应物。编辑:具体问题是这样的:…
>> Python中的运算符 - python>>运算符做什么?例如,以下操作10 >> 1 = 5有什么作用? 参考方案 它是右移运算符,将所有位“右移”一次。二进制10是1010移到右边变成0101这是5