Python diff并获得新部件
我的问题很基本 我需要区分由许多行组成的变量,只得到它们的新部分。在一个例子中理解它要简单得多: 第一个变量: 你好 我的 名字 是 第二个变量: 名字 是 彼得 及 我 上午 金发女郎 我需要摘录: 彼得 及 我 上午 金发女郎 我需要在大文件中做这件事。我怎么做Python diff并获得新部件,python,compare,diff,Python,Compare,Diff,我的问题很基本 我需要区分由许多行组成的变量,只得到它们的新部分。在一个例子中理解它要简单得多: 第一个变量: 你好 我的 名字 是 第二个变量: 名字 是 彼得 及 我 上午 金发女郎 我需要摘录: 彼得 及 我 上午 金发女郎 我需要在大文件中做这件事。我怎么做 非常感谢。如果重复和顺序无关紧要,这很简单: first = set(open('firstFile').readlines()) second = set(open('secondFile').readlines()) diff
非常感谢。如果重复和顺序无关紧要,这很简单:
first = set(open('firstFile').readlines())
second = set(open('secondFile').readlines())
diff = second - first
如果输出顺序重要:
first = open('firstfile').readlines()
second = open('secondFile').readlines()
diff = [line for line in second if line not in first]
如果输入顺序很重要,则需要澄清问题
如果文件太大,将其加载到内存中是个坏主意,则可能必须执行以下操作:
secondFile = open('secondFile')
diffFile = open('diffFile')
for secondLine in secondFile:
match = False
firstFile = open('firstFile')
for firstLine in firstFile:
if firstLine == secondLine:
match = True
break
firstfile.close()
if not match:
print >>diffFile, secondLine
secondFile.close()
根据对该问题的评论,可以这样做:
first = set(x.strip() for x in open("tmp1.txt").readlines())
second = set(x.strip() for x in open("tmp2.txt").readlines())
print second - first
first = set(x.strip() for x in open("tmp1.txt").readlines())
for line in open("tmp2.txt").xreadlines():
line = line.strip()
if line not in first:
print line
但是,如果我们认真对待“大”文件,在处理之前加载整个文件可能会占用比机器上可用的内存更多的内存。如果第一个文件足够小,可以放入内存,而第二个文件不够小,则可以执行以下操作:
first = set(x.strip() for x in open("tmp1.txt").readlines())
second = set(x.strip() for x in open("tmp2.txt").readlines())
print second - first
first = set(x.strip() for x in open("tmp1.txt").readlines())
for line in open("tmp2.txt").xreadlines():
line = line.strip()
if line not in first:
print line
如果第一个文件太大,我认为您需要求助于数据库。拆分行并设置差异是,但如果我设置(variable1)-set(variable2),我将得到
Hello
和my
。我只想买一个新的。无论如何,谢谢尝试设置(变量2)-设置(变量1)。这是一个额外的问题。第一个参数取自文件,但第二个参数是缓冲区中的变量。对于第二个变量,我正在执行second=data.split(“\n”)
,但差异结果不正确。你知道为什么吗?