簡體   English   中英

比較兩個文本文件以查找差異並將其輸出到新的文本文件

[英]Compare two text files to find differences and output them to a new text file

我正在嘗試一個簡單的數據比較文本文檔。 目標是使用戶能夠選擇一個文件,在該文件中搜索某個參數,然后將這些參數與具有默認值的文本文檔進行比較,然后將這些參數打印到新的文本文檔中。參數,然后將它們進行比較以將差異打印到新的文本文檔中。

我創建了一個簡單的流程圖對此進行了總結:

的FlowChart

這是我當前的代碼。 我正在使用diff lib比較兩個文件。

import difflib
from Tkinter import *
import tkSimpleDialog
import tkMessageBox
from tkFileDialog import askopenfilename

root = Tk()
w = Label(root, text ="Configuration Inspector")
w.pack()
tkMessageBox.showinfo("Welcome", "This is version 1.00 of Configuration Inspector")
filename = askopenfilename() # Logs File
filename2 = askopenfilename() # Default Configuration
compareFile = askopenfilename() # Comparison File
outputfilename = askopenfilename() # Out Serial Number Configuration from Logs

with open(filename, "rb") as f_input:
    start_token = tkSimpleDialog.askstring("Serial Number", "What is the serial number?")
    end_token = tkSimpleDialog.askstring("End Keyword", "What is the end keyword")
    reText = re.search("%s(.*?)%s" % (re.escape(start_token + ",SHOWALL"), re.escape(end_token)), f_input.read(), re.S)
    if reText:
        output = reText.group(1)
        fo = open(outputfilename, "wb")
        fo.write(output)
        fo.close()

        diff = difflib.ndiff(outputfilename, compareFile)
        print '\n'.join(list(diff))

    else:
        tkMessageBox.showinfo("Output", "Sorry that input was not found in the file")
        print "not found"

到目前為止,結果是該程序可以正確搜索您選擇的文件以供搜索,然后將找到的參數打印到新的輸出文本文件中。

嘗試比較兩個文件(默認數據和輸出文件)時會出現問題。

比較時,程序將輸出差異,但是,由於默認數據文件的行與輸出文件的行不同,因此它將僅打印出不匹配的行,而不打印不匹配的參數。 換句話說,我有兩個文件:

默認數據文本文件:

Data1 = 1
Data2 = 2
Data3 = 3
Data4 = 4
Data5 = 5
Data6 = 6

輸出數據文本文件:

Data1 = 1
Data2 = 2
Data3 = 8
Data4 = 7

因此,由於Data3和Data4與Match.txt文件(比較輸出)不匹配,因此應顯示該信息。 例如:

Data3 = 8
Data4 = 7
Data5 = 5
Data6 = 6

但是,它不匹配或不比較行,它只是檢查該空間中是否有行。 所以目前我的比較輸出看起來像這樣:

Data5 = 5
Data6 = 6

關於如何進行比較的任何想法都可以顯示文件參數之間的差異嗎?

如果您需要更多詳細信息,請在評論中讓我知道,我將編輯原始帖子以添加更多詳細信息。

我不知道您要使用difflib.ndiff()做什么。 該函數接受兩個字符串列表,但是您要傳遞文件名。

無論如何,這是一個簡短的演示,可以執行所需的比較。 它使用dict來加快比較過程。 顯然,我沒有您的數據文件,因此該程序使用字符串.splitlines()方法創建字符串列表。

它逐行通過默認數據列表。
如果輸出dict不存在該數據,則將打印默認行。
如果輸出dict存在具有該值的數據鍵,那么將跳過該行。
如果找到了鍵,但是輸出dict中的值與默認值不同,則將打印包含鍵和輸出值的行。

#Build default data list
defdata = '''
Data1 = 1
Data2 = 2
Data3 = 3
Data4 = 4
Data5 = 5
Data6 = 6
'''.splitlines()[1:]

#Build output data list
outdata = '''
Data1 = 1
Data2 = 2
Data3 = 8
Data4 = 7
'''.splitlines()[1:]

outdict = dict(line.split(' = ') for line in outdata)

for line in defdata:
    key, val = line.split(' = ')
    if key in outdict:
        outval = outdict[key]
        if outval != val:
            print '%s = %s' % (key, outval)
    else:
        print line

產量

Data3 = 8
Data4 = 7
Data5 = 5
Data6 = 6

這是將文本文件讀入行列表的方法。

with open(filename) as f:
    data = f.read().splitlines()

還有一個.readlines()方法,但是在這里不是那么有用,因為它在每行的末尾保留\\n行字符,我們不希望這樣。

請注意,如果文本文件中有任何空白行,則結果列表在該位置將有一個空字符串'' 而且,該代碼不會刪除每行上的任何前導或尾隨空格或其他空格。 但是,如果您需要這樣做,那么有成千上萬的示例可以向您展示如何在Stack Overflow上進行操作。


版本2

此新版本使用略有不同的方法。 它遍歷在默認列表或輸出列表中找到的所有鍵的排序列表。
如果僅在列表之一中找到鍵,則將相應的行添加到差異列表中。
如果在兩個列表中都找到了一個鍵,但是輸出行與默認行不同,則將輸出列表中的相應行添加到差異列表中。 如果兩行相同,則不向差異列表添加任何內容。

#Build default data list
defdata = '''
Data1 = 1
Data2 = 2
Data3 = 3
Data4 = 4
Data5 = 5
Data6 = 6
'''.splitlines()[1:]

#Build output data list
outdata = '''
Data1 = 1
Data2 = 2
Data3 = 8
Data4 = 7
Data8 = 8
'''.splitlines()[1:]

def make_dict(data):
    return dict((line.split(None, 1)[0], line) for line in data)

defdict = make_dict(defdata)
outdict = make_dict(outdata)

#Create a sorted list containing all the keys
allkeys = sorted(set(defdict) | set(outdict))
#print allkeys

difflines = []
for key in allkeys:
    indef = key in defdict
    inout = key in outdict
    if indef and not inout:
        difflines.append(defdict[key])
    elif inout and not indef:
        difflines.append(outdict[key])
    else:
        #key must be in both dicts
        defval = defdict[key]
        outval = outdict[key]
        if outval != defval:
            difflines.append(outval)

for line in difflines:
    print line

產量

Data3 = 8
Data4 = 7
Data5 = 5
Data6 = 6
Data8 = 8

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM