如何在python中比较两个文件中的行相同或不同

时间:2013-12-18 05:26:59

标签: python python-2.7 python-3.x

我有两个文件,其中包含以下几行:

file1:
6.959999999:    LOG_MOD_L0_RECEIVE_TXBRP_CONTROL(0, 
 0x0059005f, 
 0x0049006d, 
 0x00b9008b, 
 0x001300b9)
7.959999999:    LOG_MOD_L0_RECEIVE_TXBRP_Measure(1, 
 0x0059005m, 
 0x0049006d, 
 0x04b9008b, 
 0x001300b9)

file2:
6.959999999:    01_LOG_MOD_L0_RECEIVE_TXBRP_CONTROL(0, 
 0x0059005f, 
 0x0049006d, 
 0x00b9008b, 
 0x001300b9)
7.959999999:    LOG_MOD_L0_RECEIVE_TXBRP_Measure(1, 
 0x0059005m, 
 0x0049006d, 
 0x04b9008b, 
 0x001300b9)

在此,如果我为文件2提供file1的输入字符串为“LOG_MOD_L0_RECEIVE_TXBRP_CONTROL”和“01_LOG_MOD_L0_RECEIVE_TXBRP_CONTROL”。我想检查内部存在的数据是相同还是不同。我的意思是我必须检查

(0, 
 0x0059005f, 
 0x0049006d, 
 0x00b9008b, 
 0x001300b9)

此数据和

(0, 
 0x0059005f, 
 0x0049006d, 
 0x00b9008b, 
 0x001300b9)

这些数据是否相同。

我的代码是:

file1=open("C:\\Python27\\output1.txt","r")
file2=open("C:\\Python27\\output2.txt","r")
lines1=file1.readlines()
lines2=file2.readlines()

output1_string=raw_input("Enter the String of file1:")
output2_string=raw_input("Enter the String of file2:")
for line1 in lines1:
    for line2 in lines2:
      if line1==line2:
         print "both are same"
      else:
         print "Different"

3 个答案:

答案 0 :(得分:1)

两个问题:

output1_string=raw_input("Enter the String of file1:")
output2_string=raw_input("Enter the String of file2:")

从未使用过,似乎毫无意义,但最重要的是:

same = set(file1).intersection(file2)

您需要读取某个地方的文件内容来比较它们,您需要将两个集合与一个集合进行比较。

还有一个python库可以为你做这个 - 看看difflib

答案 1 :(得分:1)

#!/usr/bin/env python3

import re
lines1=open("output1.txt","rt").read()
lines2=open("output2.txt","rt").read()
hits1 = re.findall(r'\(.*?\)', lines1, re.DOTALL)
hits2 = re.findall(r'\(.*?\)', lines2, re.DOTALL)
print('equal:', set(hits1).intersection(hits2))
print('diff: ', set(hits1).difference(hits2))

打印

equal: {'(0, \n 0x0059005f, \n 0x0049006d, \n 0x00b9008b, \n 0x001300b9)', '(1, \n 0x0059005m, \n 0x0049006d, \n 0x04b9008b, \n 0x001300b9)'}
diff:  set()

答案 2 :(得分:1)

首先,您需要解决找到正确匹配部分的问题。以下生成器函数将生成您要查找的部分信息:

def find_sections(filename, text):
    with open(filename) as fin:
        section = None
        for line in fin:
            if text in line:
                section = line.rpartition('(')[-2:]
                try:
                    while ')' not in line:
                        line = next(fin)
                        section.append(line)
                except StopIteration:
                    pass  # ran out of file to read
                yield ''.join(section)
            else:
                previous = line

要测试两个文件中是否存在相同的数据,请先读取一个并收集集合中的所有数据:

output1_string=raw_input("Enter the String of file1:")
sections1 = set(find_sections("C:\\Python27\\output1.txt", output1_string))

现在,您可以通过设置交集来查找其他文件中的匹配条目:

output2_string=raw_input("Enter the String of file2:")
sections2 = find_sections("C:\\Python27\\output2.txt", output1_string)
for match in sections1.intersection(sections2):
    print 'Found a match:'
    print match