Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python部分比较两个文件_Python - Fatal编程技术网

Python部分比较两个文件

Python部分比较两个文件,python,Python,我有两个输入文件: 投入1: 好的句子 双跑道 三跑道 右跑道 一种途径 四通路 零通路 投入2: 好的句子 双跑道 三跑道 右跑道 零通路 一种途径 四通路 我使用了以下代码: 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:

我有两个输入文件:

投入1:

好的句子
双跑道
三跑道
右跑道
一种途径

四通路
零通路

投入2:

好的句子
双跑道
三跑道
右跑道
零通路

一种途径
四通路

我使用了以下代码:

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)
预计产量为:

一种途径

零通路


但是我得到的输出是空的。问题是我不知道如何将文件中的内容部分存储到列表中,然后进行比较,最后从列表中读取。有人能在这方面帮助我吗?

如果您只想在两个文件中都有公共文本行,那么set将提供一种很好的方法。大概是这样的:

content1 = set(open("file1", "r"))
content2 = set(open("file2", "r"))
diff_items = content1.difference(content2)
更新:但问题是关于差异的,与
diff
实用程序的意义相同吗?也就是说,顺序很重要(如示例所示)。

使用

不使用您自己的方法设置:

with open('output_ref.txt', 'r') as file1:
    with open('output_ref1.txt', 'r') as file2:
        f1 = [x.strip() for x in file1]
        f2 = [x.strip() for x in file2]
        five_f1 = f1[0:5]
        two_f1 = f1[5:]
        five_f2 = f2[0:5]
        two_f2 = f2[5:]
        same = diff(five_f1,five_f2) + diff(two_f1,two_f2)
        print same
['one pathway', 'zero pathway']

您好,感谢您的回复,我不想使用集合,而是需要部分存储文件的前半部分,并与另一个文件的前半部分进行比较,然后以迭代的方式进行。你能在这方面帮助我吗?你的输出没有意义,你的函数正在做的是向y添加a中的项,而不是b中的项,这正是s.difference所做的,重写你的问题以准确显示你对输出的期望I,谢谢你的回答,我不想使用集合,相反,我需要部分存储文件的前半部分,并与另一个文件的前半部分进行比较,然后以迭代的方式进行。你能帮我吗?你想从文件中得到什么行?在第一部分(前五行)中,第二个文件的前半部分缺少“一条路径”。在第二部分,“零路径”缺失。因此,这两行是文件的预期输出。。你能帮我弄到这个吗。。。
with open('output_ref.txt', 'r') as file1:
    with open('output_ref1.txt', 'r') as file2:
        f1 = [x.strip() for x in file1]
        f2 = [x.strip() for x in file2]
        five_f1 = f1[0:5]
        two_f1 = f1[5:]
        five_f2 = f2[0:5]
        two_f2 = f2[5:]
        same = diff(five_f1,five_f2) + diff(two_f1,two_f2)
        print same
['one pathway', 'zero pathway']