【发布时间】:2018-02-27 09:55:22
【问题描述】:
我有两个文件:fileA 和 fileB。我想获取 fileA 中存在的 fileB 中所有行的行号。但是如果一行确实在 fileA 中,我不会将其识别为“存在于 fileA 中”,除非下一行也在其中。所以我写了以下代码:
def compare_two(fileA, fileB):
with open(fileA, 'r') as fa:
fa_content = fa.read()
with open(fileB, 'r') as fb:
keep_line_num = [] # the line number that's not in fileA
i = 1
while True:
line = fb.readline()
if line == '': # There are no blank lines in both files
break
last_pos = fb.tell()
theFollowing = line
new_line = fb.readline() # get the next line
theFollowing += new_line
fb.seek(last_pos)
if theFollowing not in fa_content:
keep_line_num.append(i)
i += 1
fb.close()
fa.close()
return keep_line_num
compare_two(fileA, fileB)
这适用于小文件。但是我想将它用于大至 2GB 的大文件,这种方法对我来说太慢了。在 Python2.7 中还有其他方法可以解决这个问题吗?
【问题讨论】:
-
尝试构建一个查找字典,使用 A 中的行作为键,行号作为值。查找应变为
O(log(#line))而不是O(filesize)。不过不太确定,所以评论而不是回答。 -
我不确定使用 python 能真正做到多好。即使您要使用字典,我仍然认为它会很慢。您也许可以通过多处理来做一些超级花哨的事情。如果速度是你所追求的,那么尝试用 Golang 或 C++ 之类的东西编写它可能是明智的
-
为什么不对每一行的一小部分进行散列,寻找完全相同的值,然后比较匹配的整行?如果线条通常有点长,它可能会更快
标签: python python-2.7 text-processing