在非常大的 HTML 文件上使用 BeautifulSoup - 内存错误?

Using BeautifulSoup on very large HTML file - memory error?

我正在通过参与一个项目 - Facebook 消息分析器来学习 Python。我下载了我的数据,其中包括一个包含我所有消息的 messages.htm 文件。我正在尝试编写一个程序来解析此文件并输出数据(消息数、最常用词等)

但是,我的 messages.htm 文件是 270MB。在 shell 中创建一个 BeautifulSoup 对象进行测试时,任何其他文件(所有 < 1MB)都可以正常工作。但是我无法创建 messages.htm 的 bs 对象。这是错误:

>>> mf = open('messages.htm', encoding="utf8")
>>> ms = bs4.BeautifulSoup(mf)
Traceback (most recent call last):
  File "<pyshell#73>", line 1, in <module>
    ms = bs4.BeautifulSoup(mf)
  File "C:\Program Files (x86)\Python\lib\site-packages\bs4\__init__.py", line 161, in __init__
markup = markup.read()
  File "C:\Program Files (x86)\Python\lib\codecs.py", line 319, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
MemoryError

所以我什至不能开始使用这个文件。这是我第一次处理这样的事情,我只是在学习 Python 所以任何建议都将不胜感激!

由于您将其用作学习练习,因此我不会提供太多代码。您最好使用 ElementTree's iterparse 允许您在解析时进行处理。 BeautifulSoup 据我所知没有此功能。

入门指南:

import xml.etree.cElementTree as ET

with open('messages.htm') as source:

    # get an iterable
    context = ET.iterparse(source, events=("start", "end"))

    # turn it into an iterator
    context = iter(context)

    # get the root element
    event, root = context.next()

    for event, elem in context:
        # do something with elem

        # get rid of the elements after processing
        root.clear()

如果您打算使用 BeautifulSoup,您可以考虑将源 HTML 拆分为可管理的块,但您需要小心保持线程消息结构和确保你保持有效 HTML.