gpt4 book ai didi

python - 在 python 中删除标签

转载 作者:行者123 更新时间:2023-12-01 05:07:16 26 4
gpt4 key购买 nike

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

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

最佳答案

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 ' 是一个棘手的问题,因为如果 <tag1><b>那么它会被用户代理渲染为 hellothere,没有任何中间空间;需要解析 CSS 才能知道哪些元素应该是内联的,哪些不是。

但是,如果我们允许每个非文本节点(和结束标签)被空格替换,那么粗略的做法是使用 soup.findChildren 单独搜索所有文本节点。 ,分别拆分每个列表,将这些列表与 itertools.chain 合并然后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'

关于python - 在 python 中删除标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24776323/

26 4 0