剥离html标签之间的空间

时间:2013-11-23 11:28:12

标签: python regex space strip

我有一个包含一些html标签的字符串,如下所示:

"<p>   This is a   test   </p>"

我想剥去标签之间的所有额外空格。我尝试过以下方法:

In [1]: import re

In [2]: val = "<p>   This is a   test   </p>"

In [3]: re.sub("\s{2,}", "", val)
Out[3]: '<p>This is atest</p>'

In [4]: re.sub("\s\s+", "", val)
Out[4]: '<p>This is atest</p>'

In [5]: re.sub("\s+", "", val)
Out[5]: '<p>Thisisatest</p>'

但无法获得所需的结果,即<p>This is a test</p>

我怎样才能实现这个目标?

6 个答案:

答案 0 :(得分:4)

尝试使用像BeautifulSoup这样的HTML解析器:

from bs4 import BeautifulSoup as BS
s = "<p>   This is a   test   </p>"
soup = BS(s)
soup.find('p').string =  ' '.join(soup.find('p').text.split())
print soup

返回:

<p>This is a test</p>

答案 1 :(得分:1)

尝试

re.sub(r'\s+<', '<', val)
re.sub(r'>\s+', '>', val)

然而,这对于一般的现实世界使用而言过于简单化,其中如果标记,则不一定总是将代码放在一边。 (想想<code>块,<script>块等等。)你应该使用适当的HTML解析器来做类似的事情。

答案 2 :(得分:1)

从问题中,我看到您正在使用非常具体的HTML字符串进行解析。虽然正则表达式快速而且脏,但 its not recommend -- use a XML parser instead 。注意:XML比HTML更严格。因此,如果您认为自己可能没有XML,请使用BeautifulSoup作为@Haidro建议。

对于你的情况,你会做这样的事情:

>>> import xml.etree.ElementTree as ET
>>> p = ET.fromstring("<p>   This is a   test   </p>")
>>> p.text.strip()
'This is a   test'
>>> p.text = p.text.strip()  # If you want to perform more operation on the string, do it here.
>>> ET.tostring(p)
'<p>This is a   test</p>'

答案 3 :(得分:0)

这可能有所帮助:

import re

val = "<p>   This is a   test   </p>"
re_strip_p = re.compile("<p>|</p>")

val = '<p>%s</p>' % re_strip_p.sub('', val).strip()

答案 4 :(得分:0)

你可以试试这个:

re.sub(r'\s+(</)|(<[^/][^>]*>)\s+', '$1$2', val);

答案 5 :(得分:0)

s = '<p>   This is a   test   </p>'
s = re.sub(r'(\s)(\s*)', '\g<1>', s)
>>> s
'<p> This is a test </p>'
s = re.sub(r'>\s*', '>', s)
s = re.sub(r'\s*<', '<', s)
>>> s
'<p>This is a test</p>'