Python diff并获得新的p

2024-03-29 15:30:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题很基本。你知道吗

我需要区分由许多行组成的变量,只得到其中的新部分。用一个例子来理解它要简单得多:

第一个变量:

Hello

my

name

is

第二个变量:

name

is

peter

and

I

am

blonde

我需要提取:

peter

and

I

am

blonde

我需要在大文件里做。我该怎么做?你知道吗

非常感谢。你知道吗


Tags: and文件namehelloismyam例子
2条回答

如果重复和顺序无关紧要,这很简单:

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

如果第一个文件太大,我想你需要求助于数据库。你知道吗

相关问题 更多 >