繁体   English   中英

如何编写第一个文本文件中不存在的第二行文本中的行?

[英]How can I write the lines from the first text file that are not present in the second text file?

我想比较两个文本文件。 第一个文本文件中的行不在第二个文本文件中。 我想复制这些行并将它们写到新的txt文件中。 我想要一个Python脚本,因为我经常这样做,并且不想经常上网查找这些新行。 我不需要确认file2中是否有一些不在file1中的东西。

我写了一些似乎不一致的代码。 我不确定自己在做什么错。

newLines = open("file1.txt", "r")
originalLines = open("file2.txt", "r")
output = open("output.txt", "w")

lines1 = newLines.readlines()
lines2 = originalLines.readlines()
newLines.close()
originalLines.close()

duplicate = False
for line in lines1:
    if line.isspace():
        continue
    for line2 in lines2:
        if line == line2:
            duplicate = True
            break

    if duplicate == False:
        output.write(line)
    else:
        duplicate = False

output.close()

对于file1.txt:

Man
Dog
Axe
Cat
Potato
Farmer

file2.txt:

Man
Dog
Axe
Cat

output.txt应该是:

Potato
Farmer

而是这样的:

Cat
Potato
Farmer

任何帮助将非常感激!

基于行为, file2.txt不以回车结束,所以内容lines2['Man\\n', 'Dog\\n', 'Axe\\n', 'Cat'] 注意缺少'Cat'的换行符。

我建议对您的行进行规范化,以便它们没有换行符,而替换为:

lines1 = newLines.readlines()
lines2 = originalLines.readlines()

与:

lines1 = [line.rstrip('\n') for line in newLines]
# Set comprehension makes lookup cheaper and dedupes
lines2 = {line.rstrip('\n') for line in originalLines}

并更改:

output.write(line)

至:

print(line, file=output)

它将为您添加换行符。 确实,最好的解决方案是完全避免内部循环,更改所有这些内容:

for line2 in lines2:
    if line == line2:
        duplicate = True
        break

if duplicate == False:
    output.write(line)
else:
    duplicate = False

只是:

if line not in lines2:
    print(line, file=output)

如果您按照我的建议对lines2使用一set ,那么无论file2.txt的大小如何,测试的成本都会从file2.txt的行数线性file2.txt到大致恒定(只要这组唯一)行可以完全放在内存中)。

更好的是,对打开的文件使用with语句,并流file1.txt而不是完全将其保存在内存中,最终结果是:

with open("file2.txt") as origlines:
    lines2 = {line.rstrip('\n') for line in origlines}

with open("file1.txt") as newlines, open("output.txt", "w") as output:
    for line in newlines:
        line = line.rstrip('\n')
        if not line.isspace() and line not in lines2:
            print(line, file=output)

您可以将numpy用于更小,更快的解决方案。 在这里,我们使用以下numpy方法np.loadtxt文档: https: //docs.scipy.org/doc/numpy/reference/produced/numpy.loadtxt.html np.setdiff1d文档: https : //docs.scipy.org/ doc / numpy-1.14.5 / reference / generated / numpy.setdiff1d.html np.savetxt文件: https : //docs.scipy.org/doc/numpy/reference/generation/numpy.savetxt.html

import numpy as np


arr=np.setdiff1d(np.loadtxt('file1.txt',dtype=str),np.loadtxt('file2.txt',dtype=str))
np.savetxt('output.txt',b,fmt='%s')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM