python - 使用 BeautifulSoup 但从大文件中获取内存错误

标签 python beautifulsoup out-of-memory

我有一个非常大的 csv 文件,其中包含几串 HTML 代码。我正在使用 BeautifulSoup 仅提取 <p> 中的代码标签。我的代码似乎适用于几个示例,除非我在完整的 csv 文件上运行它时出现内存错误。 csv 文件大约 6 GB。这是我的代码

def import_data():
    doc=[]
    with open('input_file.csv','rb') as f:
        reader=csv.reader(f)
        for row in reader:
            doc.append((row[0],row[2]))
    return doc

def main():

    data=import_data()

    desc=[]

    for i in data:
        soup = BeautifulSoup(i[1], 'html')
        desc.append([i[0],' '.join(el.string for el in soup.find_all('p', text=True))])


    with open("output_file.csv",'a') as the_file:
        writer=csv.writer(the_file,dialect='excel')
        writer.writerow(desc)

if __name__ == '__main__':
    main()

我明白为什么内存不足了,因为我基本上在两个地方保存了 6 GB 的文件(datadesc)。我知道我能够将其中之一保存在内存中,因为我能够毫无问题地导入数据。但是你会建议我如何解决这个问题?我应该尝试用 BeautifulSoup 输出替换第二列而不是使用两个结构吗?或者我应该做一些事情,我逐行读取输入文件,我读取一行,对其执行 BeautifulSoup 转换,然后导出它(所以我一次只有一行在内存中)。谢谢,

最佳答案

你的第二个建议可能是最好的,假设 CSV 中的每个项目都是它自己的独立 HTML 集,为什么不遍历 csv 的每一行,解析它,然后读取下一行,只保留当前行内存中的 CSV,而只存储 p 标签的内容?

#pseudocode
p_tags = []
for row in csv.read_lines:
   result = html_parse(row)
   p_tags.append(result)

关于python - 使用 BeautifulSoup 但从大文件中获取内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18851498/

相关文章:

Python - 如何流式传输大 (11 gb) JSON 文件以进行分解

java - "Requested array size exceeds VM limit"位于 java.io.PrintWriter.newLine

python - 使用 Pandas HDFStore 以只读模式打开文件

python - 即使存在死锁,如何强制关闭 ProcessPoolExecutor

python - 我如何在我的 Mac 上为 python 安装漂亮的汤?看到错误

python - 使用 BeautifulSoup 抓取 Google 搜索

python - 在制作大量重复子字符串时如何避免 MemoryError?

python - 将 Tensorflow 数据集转换为 2 个包含图像和标签的数组

Python matplotlib imshow 很慢

python - beautifulsoup:如何获取表头中元素的索引