【问题标题】:drop tags in python在python中删除标签
【发布时间】:2014-09-06 17:14:15
【问题描述】:

鉴于我有字符串,我该如何删除所有标签。例如:

string = hello<tag1>there</tag1> I <tag2> want to </tag2> strip <tag3>all </tag3>these tags
>>>> hello there I want to strip all these tags

【问题讨论】:

    标签: python beautifulsoup lxml


    【解决方案1】:

    text 属性是最直接的,但它只是逐字复制文本节点,因此你得到

    >>> from bs4 import BeautifulSoup
    >>> soup = BeautifulSoup("""hello<tag1>there</tag1> I <tag2> want to </tag2> strip <tag3>all </tag3>these tags""")
    >>> soup.text
    u'hellothere I  want to  strip all these tags'
    

    您可以使用压缩所有空格

    >>> ' '.join(soup.text.split())
    u'hellothere I want to strip all these tags'
    

    现在,'hello' 和 'there' 之间缺少的空格是一个棘手的问题,因为如果 &lt;tag1&gt; 是 &lt;b&gt;,那么用户代理会将其呈现为 hellothere,没有任何中间空间;需要解析 CSS 以了解哪些元素应该是内联的,哪些不是。

    但是,如果我们允许将每个非文本节点(和结束标签)替换为空格,那么粗略的做法是使用 soup.findChildren 分别搜索所有文本节点,分别拆分它们,将这些列表与 @987654328 合并@ 然后join 它们全部用一个空格作为分隔符:

    >>> from itertools import chain
    >>> words = chain(*(i.split() for i in soup.findChildren(text=True)))
    >>> ' '.join(words)
    u'hello there I want to strip all these tags'
    

    【讨论】:

    • 谢谢,但是不规则间距怎么处理??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多