【问题标题】:How can I turn <br> and <p> into line breaks?如何将 <br> 和 <p> 变成换行符?
【发布时间】:2012-05-16 12:00:45
【问题描述】:

假设我有一个带有&lt;p&gt;&lt;br&gt; 标记的HTML。之后,我将剥离 HTML 以清理标签。如何将它们变成换行符?

如果有帮助的话,我正在使用 Python 的 BeautifulSoup 库。

【问题讨论】:

  • 对如何完成有任何偏好吗?我打算建议re.sub(r"&lt;p&gt;|&lt;br&gt;", "\n", myString)
  • 那么结束标签呢?
  • &lt;/?p&gt;|&lt;br&gt; 我猜。你只想要一个换行符结束标记之后?
  • 我会跳过 Beautiful Soup,直接通过 XSLT 来代替。

标签: python html xml regex


【解决方案1】:

我不完全确定您要完成什么,但如果您只是想删除 HTML 元素,我会使用像 Notepad2 这样的程序并使用全部替换功能 - 我认为您可以也使用全部替换插入一个新行。确保如果您替换了 &lt;p&gt; 元素,您也删除了关闭 (&lt;/p&gt;)。此外,仅供参考,正确的 HTML5 是 &lt;br /&gt; 而不是 &lt;br&gt;,但这并不重要。 Python 不会是我的首选,所以它有点超出我的知识范围,抱歉我帮不上忙。

【讨论】:

    【解决方案2】:

    没有一些细节,很难确定这完全符合你的要求,但这应该会给你一个想法......它假设你的 b 标签被包裹在 p 元素中。

    from BeautifulSoup import BeautifulSoup
    import six
    
    def replace_with_newlines(element):
        text = ''
        for elem in element.recursiveChildGenerator():
            if isinstance(elem, six.string_types):
                text += elem.strip()
            elif elem.name == 'br':
                text += '\n'
        return text
    
    page = """<html>
    <body>
    <p>America,<br>
    Now is the<br>time for all good men to come to the aid<br>of their country.</p>
    <p>pile on taxpayer debt<br></p>
    <p>Now is the<br>time for all good men to come to the aid<br>of their country.</p>
    </body>
    </html>
    """
    
    soup = BeautifulSoup(page)
    lines = soup.find("body")
    for line in lines.findAll('p'):
        line = replace_with_newlines(line)
        print line
    

    运行此结果...

    (py26_default)[mpenning@Bucksnort ~]$ python thing.py
    America,
    Now is the
    time for all good men to come to the aid
    of their country.
    pile on taxpayer debt
    
    Now is the
    time for all good men to come to the aid
    of their country.
    (py26_default)[mpenning@Bucksnort ~]$
    

    【讨论】:

    【解决方案3】:

    这是@Mike Pennington 的答案的python3 版本(它真的很有帮助),我做了一个垃圾重构。

    def replace_with_newlines(element):
        text = ''
        for elem in element.recursiveChildGenerator():
            if isinstance(elem, str):
                text += elem.strip()
            elif elem.name == 'br':
                text += '\n'
        return text
    
    
    def get_plain_text(soup):
        plain_text = ''
        lines = soup.find("body")
        for line in lines.findAll('p'):
            line = replace_with_newlines(line)
            plain_text+=line
        return plain_text
    

    要使用它,只需将 Beautifulsoup 对象传递给 get_plain_text 方法。

    soup = BeautifulSoup(page)
    plain_text = get_plain_text(soup)
    

    【讨论】:

      【解决方案4】:

      get_text 似乎可以满足您的需求

      >>> from bs4 import BeautifulSoup
      >>> doc = "<p>This is a paragraph.</p><p>This is another paragraph.</p>"
      >>> soup = BeautifulSoup(doc)
      >>> soup.get_text(separator="\n")
      u'This is a paragraph.\nThis is another paragraph.'
      

      【讨论】:

      • 并非如此:get_text(separator='\n') 在 all 标记之后插入 separator。因此,例如“这是一些文本 without 换行符”变成“这是一些文本\nwithout\nlinebreaks”。是的,这很奇怪......
      【解决方案5】:

      我使用以下小型库来完成此操作:

      https://github.com/TeamHG-Memex/html-text

      pip install html-text
      

      就这么简单:

      >>> import html_text
      >>> html_text.extract_text('<h1>Hello</h1> world!')
      'Hello\n\nworld!'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-02
        • 2011-11-12
        • 1970-01-01
        • 1970-01-01
        • 2013-07-15
        • 2013-03-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多