Python 3.7:对大型数据文件进行性能调优比较

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (187)

我有两个大小为3 GB的 csv文件,用于比较和存储第三个文件中的差异。

Python代码:

with open('JUN-01.csv', 'r') as f1:
    file1 = f1.readlines()

with open('JUN-02.csv', 'r') as f2:
    file2 = f2.readlines()

with open('JUN_Updates.csv', 'w') as outFile:
    outFile.write(file1[0])
    for line in file2:
        if line not in file1:
            outFile.write(line)

执行时间:45分钟仍然在运行......

提问于
用户回答回答于

不确定是否已经太晚了,但它来了。

我看到你正在内存中加载2个数组,包含完整的文件。如果你说它们各自大约3 GB,那就是尝试在RAM中填充6 GB并且可能进入交换。

此外,即使您成功加载文件,您也在尝试~L1xL2字符串比较(L1和L2是行数)。

我已经在1.2 GB(330万行)中运行以下代码,并在几秒钟内完成。它使用字符串哈希,并且只在RAM中加载一组L1 integer32。

诀窍是在这里完成的,在将hashstring函数应用于文件中的每一行之后创建一个set()(除了标题,你似乎要添加到输出中)。

file1 = set(map(hashstring, f1))

请注意我将文件与自身进行比较(f2加载与f1相同的文件)。如果有帮助,请告诉我。

from zlib import adler32

def hashstring(s):
    return adler32(s.encode('utf-8'))

with open('haproxy.log.1', 'r') as f1:
    heading = f1.readline()
    print(f'Heading: {heading}')
    print('Hashing')
    file1 = set(map(hashstring, f1))
    print(f'Hashed: {len(file1)}')

with open('updates.log', 'w') as outFile:
    count = 0
    outFile.write(heading)
    with open ('haproxy.log.1', 'r') as f2:
        for line in f2:
            if hashstring(line) not in file1:
                outFile.write(line)
            count += 1
            if 0 == count % 10000:
                print(f'Checked: {count}')
用户回答回答于

如果difflib可以提高效率,请尝试以下方法: -

import difflib
import sys

with open('JUN_Updates.csv', 'w') as differenceFile:
    with open('JUN-01.csv', 'r') as june1File:
        with open('JUN-02.csv', 'r') as june2File:
            diff = difflib.unified_diff(
                june1File.readlines(),
                june2File.readlines(),
                fromfile='june1File',
                tofile='june2File',
            )

            lines = list(diff)[2:]
            added = [line[1:] for line in lines if line[0] == '+']
            removed = [line[1:] for line in lines if line[0] == '-']

            for line in added:
                differenceFile.write(line)

扫码关注云+社区

领取腾讯云代金券