1

我正在尝试搜索 filetwos 的内容,看看它是否包含给定搜索词的任何重复项(来自 fileone 的行)。如果它包含重复项,它将什么也不做,但如果它不包含重复项,我希望它附加一行。

fileone.txt(两行)

[('123', 'aaa')]

[('900', 'abc')]

文件二.txt

[('123', 'aaa')]

[('999', 'zzz')]

我下面的代码将这些行添加到 filetwo,即使它们是重复的。我无法弄清楚这一点!

with open('fileone.txt', 'r') as f:
seen = open('filetwo.txt', 'a+')
for line in f:
    if line in seen:
        print(line + 'is a duplicate')
    else:
        seen.write(line)

f.close()
seen.close()
4

1 回答 1

2

您不能只搜索给定行if line in seen:的整个文件。seen即使可以,它也只会搜索文件的其余部分,并且由于您位于文件的末尾,这意味着您什么都没有搜索。而且,即使你解决了这个问题,它仍然需要对整个文件的每一行进行线性搜索,这将非常慢。

最简单的做法是跟踪看到的所有行,例如,使用set:

with open('filetwo.txt') as f:
    seen = set(f)

with open('fileone.txt') as fin, open('filetwo.txt', 'a+') as fout:
    for line in fin:
        if line in seen:
            print(line + 'is a duplicate')
        else:
            fout.write(line)
            seen.add(line)

请注意,我在开始之前预先填充seen了所有行,filetwo.txt然后在我们进行时添加每个新行seen。这避免filetwo.txt了一遍又一遍地重新阅读——我们知道我们在写什么,所以记住它。

于 2013-08-29T22:07:28.960 回答