如何比较python中两个文件中的行相同或不同 [英] how to compare lines in two files are same or different in python
问题描述
我有两个文件,其中包含以下几行:
I have two files which contains following lines:
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)
在这里,如果我将文件 1 的输入字符串指定为LOG_MOD_L0_RECEIVE_TXBRP_CONTROL"和文件 2 的01_LOG_MOD_L0_RECEIVE_TXBRP_CONTROL".我想检查里面的数据是相同的还是不同的.我的意思是我必须检查
In this if i give input string for file1 as "LOG_MOD_L0_RECEIVE_TXBRP_CONTROL" and "01_LOG_MOD_L0_RECEIVE_TXBRP_CONTROL" for file 2.I want to check the data present inside is same or different.I mean i have to check
(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"
推荐答案
您首先需要解决定位正确匹配部分的问题.以下生成器函数将生成您要查找的部分信息:
You'll first need to solve the problem of locating the right, matching section. The following generator function will produce the section information you are looking for:
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
要测试两个文件中是否存在相同的数据,请先读取一个并收集一组中的所有数据:
To test if the same data exists in both files, read one first and collect all data in a set:
output1_string=raw_input("Enter the String of file1:")
sections1 = set(find_sections("C:\\Python27\\output1.txt", output1_string))
现在您可以通过设置交集在另一个文件中找到匹配的条目:
Now you can find matching entries in the other file by doing a set intersection:
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
这篇关于如何比较python中两个文件中的行相同或不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!