python删除特定标记内的文本

2024-04-26 13:56:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串中有“代码”标记,我想删除这些标记和这些标记内的所有内容。例如

"hello how are <code>this is my code</code> you"

变成

^{pr2}$

我很确定BeautifulSoup是这项工作的正确工具,但是我已经看过文档,我不知道如何做到这一点。在

谢谢


Tags: 工具字符串代码标记you内容hellois
1条回答
网友
1楼 · 发布于 2024-04-26 13:56:51

轻松使用Tag.extract()

>>> from bs4 import BeautifulSoup as BS
>>> s = "hello how are <code>this is my code</code> you"
>>> soup = BS(s)
>>> codetags = soup.find_all('code')
>>> for codetag in codetags:
...    codetag.extract()
>>> print soup
hello how are  you

相关问题 更多 >