使用Python从HTML文件中提取文本

2024-05-08 15:14:05 发布

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

我想用Python从HTML文件中提取文本。我想要基本上相同的输出,如果我将文本从浏览器复制并粘贴到记事本。

我想要比在格式不好的HTML上使用可能失败的正则表达式更健壮的东西。我见过很多人推荐靓汤,但我在使用时遇到了一些问题。一方面,它提取了不需要的文本,比如JavaScript源代码。而且,它没有解释HTML实体。例如,我希望HTML源代码中的&;39;转换为文本中的撇号,就像我将浏览器内容粘贴到记事本中一样。

更新html2text看起来很有前途。它正确处理HTML实体并忽略JavaScript。但是,它并不完全生成纯文本;它生成的标记必须转换为纯文本。它没有示例或文档,但是代码看起来很干净。


相关问题:


Tags: 文件in文本实体内容源代码粘贴html
3条回答

我找到了最好的一段代码,可以在不使用javascript或不需要的情况下提取文本:

import urllib
from bs4 import BeautifulSoup

url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)

# kill all script and style elements
for script in soup(["script", "style"]):
    script.extract()    # rip it out

# get text
text = soup.get_text()

# break into lines and remove leading and trailing space on each
lines = (line.strip() for line in text.splitlines())
# break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
# drop blank lines
text = '\n'.join(chunk for chunk in chunks if chunk)

print(text)

你只需要在以下之前安装美偶:

pip install beautifulsoup4

html2text是一个Python程序,在这方面做得非常好。

注意:NTLK不再支持clean_html函数

原始答案如下,并在评论部分的备选方案。


使用NLTK

我浪费了4-5个小时来解决html2text的问题。幸运的是,我可以遇到NLTK。
它神奇地工作。

import nltk   
from urllib import urlopen

url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"    
html = urlopen(url).read()    
raw = nltk.clean_html(html)  
print(raw)

相关问题 更多 >