Python:比较两个文件

时间:2014-06-17 09:45:00

标签: python

我有两个输入文件:

斯堪的纳维亚航空公司航空公司 一个n 0 flightnumber
六个0 0航班号 两个n 0 flightnumber
三个n 0 flightnumber

speedbird t航空公司航空公司 一个n 0 flightnumber
六个0 0航班号 8 n 0 flightnumber

我的第二个输入文件:

斯堪的纳维亚航空公司airli
一个n 0 flightnumber
六个0 0航班号 两个n 0 flightnumber
三个n 0 flightnumber

六个0 0航班号 8 n 0 flightnumber

我有以下代码:

with open('output_ref.txt', 'r') as file1:
with open('output_ref1.txt', 'r') as file2:
same = set(file1).difference(file2)
print same
print "\n"

same.discard('\n')

with open('some_output_file.txt', 'w') as FO:
for line in same:
    FO.write(line)

我的输出为:

斯堪的纳维亚航空公司航空公司 speedbird t航空公司航空公司

但我的实际输出应该是:

斯堪的纳维亚航空公司航空公司 speedbird t航空公司的航空公司 一个n 0 flightnumber

有人可以帮助我解决问题吗?

2 个答案:

答案 0 :(得分:0)

首先,如果您要做的是从2个文件中获取公共行("相同的"变量名称建议),那么您应该使用交集方法而不是差异。此外,这两种方法都声明需要集合作为参数,所以我会采取额外的步骤并将第二个文件转换为集合。所以新代码应该是:

 first = set(file1)
 second = set(file2)
 same = first.intersection(second)

.....

编辑:

在我的帖子中阅读一些评论使我确信你真的想要差异而不是集合,而是列表。我想这应该适合你:

difference = list(file1)
second = list(file2)
for line in second:
    try:
        first.remove(line)
    except ValueError,e:
        print e # alternately you could just pass here

答案 1 :(得分:-1)

def diff(a, b):
    y = []
    for x in a:
        if x not in b:
            y.append(x)
        else:
            b.remove(x)
    return y

with open('output_ref.txt', 'r') as file1:
    with open('output_ref1.txt', 'r') as file2:
        same = diff(list(file1), list(file2))
        print same
        print "\n"

if '\n' in same:
    same.remove('\n')

with open('some_output_file.txt', 'w') as FO:
    for line in same:
        FO.write(line)
$ python compare.py
['scandinavian t airline airline\n', 'speedbird t airline airline\n', 'one n 0 flightnumber\n']



$ cat some_output_file.txt 
scandinavian t airline airline
speedbird t airline airline
one n 0 flightnumber
相关问题