我有两个3GB的文本文件,每个文件大约有8000万行。它们共享99.9%相同的行(文件A有60000个唯一行,文件B有80000个唯一行)。
如何快速查找这两个文件中不同的行?是否有现成的命令行工具可以使用?我正在使用Python,但我猜想很难找到一种高效的Pythonic方法来加载文件并比较。
欢迎任何建议。
我有两个3GB的文本文件,每个文件大约有8000万行。它们共享99.9%相同的行(文件A有60000个唯一行,文件B有80000个唯一行)。
如何快速查找这两个文件中不同的行?是否有现成的命令行工具可以使用?我正在使用Python,但我猜想很难找到一种高效的Pythonic方法来加载文件并比较。
欢迎任何建议。
comm
工具。如果顺序不重要,可以使用sort file1 file2 | uniq -u
。diff
快的原因是什么? - bstpierrediff
实现通常是二次的,而排序在平均情况下通常是 n log n
(快速排序)。 - tonfaimport sys
import hashlib
file = []
lines = []
for i in range(2):
# open the files named in the command line
file.append(open(sys.argv[1+i], 'r'))
# stores the hash value and the line number for each line in file i
lines.append({})
# assuming you like counting lines starting with 1
counter = 1
while 1:
# assuming default encoding is sufficient to handle the input file
line = file[i].readline().encode()
if not line: break
hashcode = hashlib.sha512(line).hexdigest()
lines[i][hashcode] = sys.argv[1+i]+': '+str(counter)
counter += 1
unique0 = lines[0].keys() - lines[1].keys()
unique1 = lines[1].keys() - lines[0].keys()
result = [lines[0][x] for x in unique0] + [lines[1][x] for x in unique1]
mydict["hello world"] => 1
等。如果您的平均行长约为40-80个字符,则这将在10 MB左右的内存范围内。
然后读取每个文件,通过字典将其转换为数字数组。它们将轻松适应内存(2个8字节* 3GB / 60k行的文件少于1 MB的内存)。然后比较列表。您可以反转字典并使用它来打印出不同的行的文本。
编辑:
针对您的评论,以下是一个示例脚本,它在读取文件时将数字分配给唯一的行。
#!/usr/bin/python
class Reader:
def __init__(self, file):
self.count = 0
self.dict = {}
self.file = file
def readline(self):
line = self.file.readline()
if not line:
return None
if self.dict.has_key(line):
return self.dict[line]
else:
self.count = self.count + 1
self.dict[line] = self.count
return self.count
if __name__ == '__main__':
print "Type Ctrl-D to quit."
import sys
r = Reader(sys.stdin)
result = 'ignore'
while result:
result = r.readline()
print result
如果我理解正确,您想要这些文件中没有重复行。这个代码可以实现:
uniqA = set(open('fileA', 'r'))
Python有difflib,声称与其他diff实用程序相当竞争,请参见: http://docs.python.org/library/difflib.html