content 是一段html文本如何只保留文本清理掉所有 HTML
要清除HTML并保留文本,可以使用Python的BeautifulSoup库进行解析和清理。以下是一个示例代码:
from bs4 import BeautifulSoup
# 假设content是包含HTML的字符串
content = "<html><body><p>This is a <strong>sample</strong> text.</p></body></html>"
# 创建BeautifulSoup对象并解析HTML
soup = BeautifulSoup(content, "html.parser")
# 使用get_text()方法获取纯文本
text = soup.get_text()
# 打印清理后的文本
print(text)
运行以上代码,输出将是:
This is a sample text.
通过使用BeautifulSoup库的get_text()方法,可以轻松地清除HTML标签并保留文本内容。
原文地址: http://www.cveoy.top/t/topic/iOcz 著作权归作者所有。请勿转载和采集!