用BeautifulSoup打破标签边界上的单词

2024-09-28 20:19:38 发布

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

我正试图用BeautifulSoup将html解析为文本,但我遇到了一个问题:有些单词被不带空格的标记分割:

<span>word1</span><span>word2</space>

所以当我提取文本时,我有:

word1word2

有些句子还与一个句子相连:

INTODUCTION There are many...

有没有一个简单的方法来强制BeautifulSoup标签上的单词分离?也可能是我可以修复一些标签上的句子分离?你知道吗

我有几个复杂的html文件。我把它们处理成文本:

plain_texts = [BeautifulSoup(html, "html.parser").get_text() for html in htmls]

Tags: 标记文本htmlspace标签单词句子span
2条回答

你可以用replace_with()方法(docs here)修补你的汤。但这取决于HTML的结构:

from bs4 import BeautifulSoup

data = '''
<html><body><span>word1</span><span>word2</space>
'''

soup = BeautifulSoup(data, 'lxml')
for span in soup.select('span'):
    span.replace_with(span.text + ' ')

print(soup.text.strip())

这张照片:

word1 word2

您可以使用^{}

from bs4 import BeautifulSoup

html_doc = """
<!DOCTYPE html><html lang="en"><head><title>words</title></head><body><span>word1</span><span>word2</span></body></html>
"""

soup = BeautifulSoup(html_doc, 'lxml')
for span in soup.find_all('span'):
    print(span.text)

分别打印<span>标记之间的文本:

word1
word2

相关问题 更多 >