gpt4 book ai didi

python - 在 Python 中提取和清理 HTML 正文文本的最快、最无错误的方法是什么?

转载 作者:可可西里 更新时间:2023-11-01 13:50:18 25 4
gpt4 key购买 nike

我目前有两个函数可以提取 HTML <body>来自 Python 的文本并将其作为单词袋返回。他们提供等效的输出。我还清理了各种标签,否则这些标签会给我垃圾文本(例如 <script> 代码)。

def html_to_bow_bs(text):
if text is None or len(text)==0:
return []

soup = BeautifulSoup(text, "lxml",parse_only=SoupStrainer('body'))

# Remove all irrelevant tags
for elem in soup.findAll(['script','style','a']):
elem.extract()
body_text = soup.findAll("body")
if len(body_text) == 0:
return []

# Encoding. Remove extra whitespace and unprintable characters
the_text = body_text[0].get_text().encode('utf-8')
the_text = str(the_text)
the_text = the_text.strip()
the_text = re.sub(r'[^\x00-\x7F]+',' ',the_text)
return [w.lower() for w in the_text.split()]




def html_to_bow_bs_lxml(text):
if text is None or len(text)==0:
return []
body_re = re.findall('<body(.*?)</body>', text, flags=re.DOTALL)
if len(body_re) == 0:
return []
fragment = body_re[0]

# Remove irrelevant tags
fragment = re.sub(r'<script.*?</script>', ' ', fragment, flags=re.DOTALL)
fragment = re.sub(r'<style.*?</style>', ' ', fragment, flags=re.DOTALL)
text = "<body" + fragment + "</body>"
soup = BeautifulSoup(text, "lxml")

if soup is None:
return []

# Remote more irrelevant tags
for elem in soup.findAll(['a']):
elem.extract()

# Encoding. Remove extra whitespace and unprintable characters
the_text = body_text[0].get_text().encode('utf-8')
the_text = str(the_text)
the_text = the_text.strip()
the_text = re.sub(r'[^\x00-\x7F]+',' ',the_text)
return [w.lower() for w in the_text.split()]

我的主要要求是匹配输出:来自 html_to_bow_bs_lxml(text) 的单词集火柴html_to_bow_bs(text) .目前,两者在运行时间上相当;对于 330 页,它们运行大约 20 秒(慢!)。如果我移除并更换我的最后一个 soup.findAll(['a'])...extract()在我使用正则表达式的第二个函数中,我可以节省 6 秒的时间。替换 BeautifulSouplxml.etree一起可以再缩短 10 秒,使总运行时间约为 3-4 秒。但是,当用正则表达式替换时,

  1. 输出并不总是匹配。替换 BeautifulSoup 时输出不匹配或
  2. 由于 HTML 格式不正确,我的程序在处理过程中崩溃了。如何在保持正确性的同时提高速度?

我在 StackOverflow 上看到过各种关于使用 Python 提取 HTML 的建议,但这些建议可以追溯到几年前(例如 2012 年)。可以理解的是,从那时起,库进行了许多更新。

(我也尝试过 pyquery,但它并不总是能正确提取正文。)

最佳答案

为了让它变得更快,您做了很多工作 - 在使用 BeautifulSoup 优化解析时,滤汤器和 lxml 解析器通常是首先要尝试的东西。

这里是对这个特定代码的一些改进。

删除主体存在检查:

body_text = soup.findAll("body")
if len(body_text) == 0:
return []

并改用 find()

if text is None or len(text)==0: 替换为 if not text:

通过 get_text(strip=True) 剥离。


改进后的代码:

def html_to_bow_bs(text):
if not text:
return []

soup = BeautifulSoup(text, "lxml", parse_only=SoupStrainer('body'))

# Remove all irrelevant tags
for elem in soup.find_all(['script','style','a']):
elem.extract()

body = soup.find("body")
if not body:
return []

the_text = body.get_text(strip=True).encode('utf-8')
the_text = re.sub(r'[^\x00-\x7F]+', ' ', the_text)
return [w.lower() for w in the_text.split()]

这些只是微观改进,我认为它们不会改变整体性能图景。我还要研究的内容:

  • 通过 pypy 运行脚本(beautifulsoup4compatible ,但您将无法使用 lxml 解析器 - 尝试使用html.parserhtml5lib)。甚至根本不修改代码,您可能会赢得很多。

关于python - 在 Python 中提取和清理 HTML 正文文本的最快、最无错误的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35778753/

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