Python 剥离html标记之间的空间
我有一个字符串,其中包含一些html标记,如下所示:Python 剥离html标记之间的空间,python,regex,space,strip,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>
"<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>'
但我无法获得期望的结果,即这是一项测试
我怎样才能做到这一点呢?试试看
re.sub(r'\s+<', '<', val)
re.sub(r'>\s+', '>', val)
然而,对于一般的现实世界使用来说,这太简单了,因为在现实世界中,如果标记是一个标记,则代理不一定总是一部分。想想块,块等等。你应该使用一个合适的HTML解析器来处理类似的事情。试试看
re.sub(r'\s+<', '<', val)
re.sub(r'>\s+', '>', val)
然而,对于一般的现实世界使用来说,这太简单了,因为在现实世界中,如果标记是一个标记,则代理不一定总是一部分。考虑块、块等。您应该使用适当的HTML解析器来处理类似的事情。尝试使用如下HTML解析器: 返回:
<p>This is a test</p>
尝试使用HTML解析器,如: 返回:
<p>This is a test</p>
这可能有助于:
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()
这可能有助于:
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()
您可以尝试以下方法:
re.sub(r'\s+(</)|(<[^/][^>]*>)\s+', '$1$2', val);
您可以尝试以下方法:
re.sub(r'\s+(</)|(<[^/][^>]*>)\s+', '$1$2', val);
从这个问题中,我看到您正在使用一个非常特定的HTML字符串进行解析。尽管正则表达式速度快且脏。注意:XML比HTML更严格。因此,如果您觉得可能没有XML,请按照@Haidro的建议使用BeautifulSoup 对于您的情况,您可以这样做:
>>> 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>'
从这个问题中,我看到您正在使用一个非常特定的HTML字符串进行解析。尽管正则表达式速度快且脏。注意:XML比HTML更严格。因此,如果您觉得可能没有XML,请按照@Haidro的建议使用BeautifulSoup 对于您的情况,您可以这样做:
>>> 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>'