我有一个html文件,想要将空段落替换为一个空格。
mystring = "This <p></p><p>is a test</p><p></p><p></p>"
result = mystring.sub("<p></p>" , " ")
这个不起作用。
您不会后悔!利润保证!
<p>
元素的示例。lxml的HTMLParser
非常擅长处理HTML。from lxml import etree
from StringIO import StringIO
input = '''This <p> </p><p>is a test</p><p></p><p><b>Bye.</b></p>'''
parser = etree.HTMLParser()
tree = etree.parse(StringIO(input), parser)
for p in tree.xpath("//p"):
if len(p):
continue
t = p.text
if not (t and t.strip()):
p.getparent().remove(p)
print etree.tostring(tree.getroot(), pretty_print=True)
...会产生输出:
<html>
<body>
<p>This </p>
<p>is a test</p>
<p>
<b>Bye.</b>
</p>
</body>
</html>
<p>
元素,而不是用 
替换它们。使用lxml,我不确定有没有简单的方法来做到这一点,所以我创建了另一个问题来询问:
BeautifulSoup
。你链接的页面明确说明它是旧版本和历史版本,而且该模块已经不存在这些问题了。 - Eli Bendersky<p><b>This will be dropped</b></p>
,上述代码将会删除它,因为node.text
仅包含位于开始标签和第一个子元素之间的文本。 - abhaga>>> mystring = "This <p></p><p>is a test</p><p></p><p></p>"
>>> mystring.replace("<p></p>"," ")
'This <p>is a test</p> '
<P>
、< p >
或者加有属性,或者是使用空标签语法 <P/>
的情况下,会发生什么呢? Pyparsing 的 HTML 标签支持可以处理所有这些变化:from pyparsing import makeHTMLTags, replaceWith, withAttribute
mystring = 'This <p></p><p>is a test</p><p align="left"></p><P> </p><P/>'
p,pEnd = makeHTMLTags("P")
emptyP = p.copy().setParseAction(withAttribute(empty=True))
null_paragraph = emptyP | p+pEnd
null_paragraph.setParseAction(replaceWith(" "))
print null_paragraph.transformString(mystring)
输出:
This <p>is a test</p>
使用正则表达式吗?
import re
result = re.sub("<p>\s*</p>"," ", mystring, flags=re.MULTILINE)
如果你经常使用正则表达式,就把它编译一下。
我写了那段代码:
from lxml import etree
from StringIO import StringIO
html_tags = """<div><ul><li>PID temperature controller</li> <li>Smart and reliable</li> <li>Auto-diagnosing</li> <li>Auto setting</li> <li>Intelligent control</li> <li>2-Rows 4-Digits LED display</li> <li>Widely applied in the display and control of the parameter of temperature, pressure, flow, and liquid level</li> <li> </li> <p> </p></ul> <div> </div></div>"""
document = etree.iterparse(StringIO(html_tags), html=True)
for a, e in document:
if not (e.text and e.text.strip()) and len(e) == 0:
e.getparent().remove(e)
print etree.tostring(document.root)