![](/img/trans.png)
[英]How to remove all lines from a large text file (>60GB) that contains a specific alphabet in python?
[英]How to check for reversed order string tuple and eliminate them from a large text file (>60GB) file in python?
我有以下代码来查找逆序字符串元组并将它们从文本文件中删除。 但是大文本文件(> 60GB)花费了无限的时间并且我的系统崩溃了。
with open("OUTPUT.txt.txt", "w") as output:
for fileName in ["Large_INPUT.txt"]:
found_combinations = set()
with open(fileName, 'r') as file1:
for line in file1:
cols = [col.strip() for col in line.strip().split('\t')]
new_combination = frozenset(cols)
if new_combination not in found_combinations:
found_combinations.add(new_combination)
out = ', '.join(cols) + '\n'
output.write(out)
例如,如果输入是:
352_0F, 352_1F, 0.913
352_1F, 352_0F, 0.913
预期的输出是:
352_0F, 352_1F, 0.913
有没有办法针对大文件优化此代码?
对于程序崩溃,我怀疑您的设备正在破坏其最大容量。 对于 22 个字符行,一个 65GB 的文件将在集合中生成接近 30 亿个条目(假设您没有很大比例的重复行)。 这根本不适合 32 位系统(因此请确保您在具有大量内存的 64 位系统上运行)
对于性能,您应该检查进程是否受 CPU 限制或 I/O 限制。 即使不做任何处理,一次读取一行大文件也可能需要很长时间。 取一个不会导致程序崩溃的文件(或为了测试而减少一个文件),并测量简单地输入一个文件并输出同一个文件(没有任何过滤)所需的时间。 这将是您可以通过逐行处理获得的最短时间。 如果这接近过滤所需的时间,那么您就有了 I/O 问题。 确保您使用的是 SSD 存储将是第一步。 您也可以尝试这里提出的解决方案(虽然我不确定它是否适用于您的环境): https : //stackoverflow.com/a/60571361/5237560
列表中只有 3 个值,因此有机会使用字典将集合分解为更小的对象。 假设元组反转只发生在前两个值之间,您可以按第三个值对集合进行分组。 这将限制设置大小(假设您有多种这些值)
例如:
from collections import defaultdict
...
for line in file1:
seenTuples = defaultdict(set)
code1,code2,value = [col.strip() for col in line.strip().split('\t')]
if code1>code2 : code1,code2 = code2,code1
if (code,code2) in seenTuples[value]: continue # skip this line
seenTuples[value].add((code1,code2))
output.write(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.