gpt4 book ai didi

python - 从大文件中剥离 html 比 BeautifulSoup 更快/更少的资源破坏方式?或者,使用 BeautifulSoup 的更好方法?

转载 作者:太空狗 更新时间:2023-10-29 15:29:19 28 4
gpt4 key购买 nike

目前我无法输入这个,因为根据 top,我的处理器是 100%,我的内存是 85.7%,都被 python 占用了。

为什么?因为我让它通过一个 250 兆的文件来删除标记。 250兆,就是这样!我一直在用 python 使用许多其他模块和东西来处理这些文件; BeautifulSoup 是第一个给我带来如此小的问题的代码。如何将近 4 GB 的 RAM 用于处理 250 兆的 html?

我发现(在 stackoverflow 上)并一直在使用的单行代码是这样的:

''.join(BeautifulSoup(corpus).findAll(text=True))

此外,这似乎删除了除标记之外的所有内容,这与我想要做的有点相反。我确信 BeautifulSoup 也可以做到这一点,但速度问题仍然存在。

有没有什么可以做类似的事情(删除标记,可靠地)并且不需要 Cray 来运行?

最佳答案

lxml.html 的效率要高得多。

http://lxml.de/lxmlhtml.html

enter image description here

http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/

看起来这会做你想做的事。

import lxml.html
t = lxml.html.fromstring("...")
t.text_content()

其他几个类似的问题:python [lxml] - cleaning out html tags

lxml.etree, element.text doesn't return the entire text from an element

Filter out HTML tags and resolve entities in python

更新:

您可能想要清理 HTML 以删除所有脚本和 CSS,然后使用 .text_content() 提取文本

from lxml import html
from lxml.html.clean import clean_html

tree = html.parse('http://www.example.com')
tree = clean_html(tree)

text = tree.getroot().text_content()

(来自:Remove all html in python?)

关于python - 从大文件中剥离 html 比 BeautifulSoup 更快/更少的资源破坏方式?或者,使用 BeautifulSoup 的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4781833/

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