gpt4 book ai didi

python - 如何消除html标签?

转载 作者:行者123 更新时间:2023-11-28 22:04:04 24 4
gpt4 key购买 nike

我正在从页面中获取第一段并尝试提取适合作为标签或关键字的词。在某些段落中有链接,我想删除标签:

例如如果文本是

A <b>hex triplet</b> is a six-digit, three-<a href="/wiki/Byte"
enter code heretitle="Byte">byte</a> ...

我要删除

<b></b><a href="/wiki/Byte" title="Byte"></a>

以此结束

A hex triplet is a six-digit, three-byte ...

这样的正则表达式不起作用:

>>> text = """A <b>hex triplet</b> is a six-digit, three-<a href="/wiki/Byte"
enter code heretitle="Byte">byte</a> ..."""
>>> f = re.findall(r'<.+>', text)
>>> f
['<b>hex triplet</b>', '</a>']
>>>

执行此操作的最佳方法是什么?

我发现了几个类似的问题,但我认为没有一个能解决这个特定问题。

使用 BeautifulSoup 提取的示例进行更新(提取会删除包括其文本在内的标签,并且必须分别为每个标签运行:

>>> soup = BeautifulSoup(text)
>>> [s.extract() for s in soup('b')]
[<b>hex triplet</b>]
>>> soup
A is a six-digit, three-<a href="/wiki/Byte" enter code heretitle="Byte">byte</a> ...
>>> [s.extract() for s in soup('a')]
[<a href="/wiki/Byte" enter code heretitle="Byte">byte</a>]
>>> soup
A is a six-digit, three- ...
>>>

更新

对于有相同问题的人:如 Brendan Long 所述,this answer使用 HtmlParser 效果最好。

最佳答案

Beautiful Soup是您问题的答案!试试看,它非常棒!

一旦你使用它,HTML 解析就会变得如此简单。

>>> text = """A <b>hex triplet</b> is a six-digit, three-<a href="/wiki/Byte"
... enter code heretitle="Byte">byte</a> ..."""
>>> soup = BeautifulSoup(text)
>>> ''.join(soup.findAll(text=True))
u'A hex triplet is a six-digit, three-byte ...'

如果您将要提取的所有文本都包含在一些外部标签中,例如 <body> ... </body>或一些 <div id="X"> .... </div> , 然后您可以执行以下操作(此图假设您要提取的所有文本都包含在 <body> 标记内)。现在您可以有选择地仅从一些所需的标签中提取文本。

(看看文档和例子,你会发现很多解析DOM的方法)

>>> text = """<body>A <b>hex triplet</b> is a six-digit, 
... three-<a href="/wiki/Byte"
... enter code heretitle="Byte">byte</a>
... </body>"""
>>> soup = BeautifulSoup(text)
>>> ''.join(soup.body.findAll(text=True))
u'A hex triplet is a six-digit, three-byte'

关于python - 如何消除html标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7775800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com