1
鉴于我有字符串,我如何放弃所有标签。例如:在python中放置标签
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中放置标签
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
文本属性是最简单的一个,但它只是复制文本节点逐字,这样你可以获得
>>> 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>
那么它将由用户代理作为你好存在,而没有任何中介空间;需要解析CSS来知道哪些元素应该内联,哪些不内联。
但是,如果我们允许每个非文本节点(和结束标记)受空间所取代,粗之一将是与soup.findChildren
分别搜索所有文本节点,分别拆分他们每个人,与itertools.chain
然后合并这些列表它们全部与单个空格一起作为分隔符:
>>> 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'
谢谢,但是如何处理不规则的间距? – Edpy