我有两个输入文件:
斯堪的纳维亚航空公司
1n0飞行数
6n0飞行数
2n0飞行数
3n0飞行数
飞鸟航空公司
1n0飞行数
6n0飞行数
8n0飞行数
我的第二个输入文件:
斯堪的纳维亚航空公司
1n0飞行数
6n0飞行数
2n0飞行数
3n0飞行数
6n0飞行数
8n0飞行数
我有以下代码:
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)我得到的输出是:
斯堪的纳维亚航空公司
飞鸟航空公司
但我的实际产出应该是:
斯堪的纳维亚航空公司
飞鸟航空公司
1n0飞行数
有人能帮我解决这个问题吗?
发布于 2014-06-17 10:24:37
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发布于 2014-06-17 10:00:29
首先,如果您试图从2个文件(“相同”变量名所指的)中获取公共行,那么您应该使用交集方法而不是差异。另外,这两种方法都要求set作为它们的参数,因此我将进行额外的步骤,并将第二个文件也转换为一个集合。因此,新的代码应该是:
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 herehttps://stackoverflow.com/questions/24260548
复制相似问题