我想比較兩個文本文件,並輸出比較文件中的第一個字符串,但是由於我對python非常陌生,所以難以匹配。任何人都可以給我一個樣本來使用這個模塊。在Python中使用difflib比較兩個.txt文件
當我嘗試類似:
result = difflib.SequenceMatcher(None, testFile, comparisonFile)
我得到一個錯誤說類型「文件」的對象沒有LEN。
我想比較兩個文本文件,並輸出比較文件中的第一個字符串,但是由於我對python非常陌生,所以難以匹配。任何人都可以給我一個樣本來使用這個模塊。在Python中使用difflib比較兩個.txt文件
當我嘗試類似:
result = difflib.SequenceMatcher(None, testFile, comparisonFile)
我得到一個錯誤說類型「文件」的對象沒有LEN。
首先,你需要爲字符串傳遞給difflib.SequenceMatcher,而不是文件:
# Like so
difflib.SequenceMatcher(None, str1, str2)
# Or just read the files in
difflib.SequenceMatcher(None, file1.read(), file2.read())
那將反正改正錯誤。爲了獲得第一個不匹配的字符串,我會引導你到美好的世界difflib documentation.
你確定兩個文件都存在嗎?
只是測試它,我得到了一個完美的結果。
得到我使用類似的結果:
import difflib
diff=difflib.ndiff(open(testFile).readlines(), open(comparisonFile).readlines())
try:
while 1:
print diff.next(),
except:
pass
每一行的第一個字符表示,如果它們是不同的: 如:「+」是指以下行已添加等
哎呀,你對的愚蠢的錯誤。但我仍然不確定如何從結果中獲取我需要的數據。我怎麼知道他們是否存在差異?我怎樣才能得到不同的第一個字符串?對不起,很多問題:( – VeePee 2009-06-10 19:09:00
聽起來你可能根本不需要difflib。如果你通過線對比線,嘗試這樣的事情:
test_lines = open("test.txt").readlines()
correct_lines = open("correct.txt").readlines()
for test, correct in zip(test_lines, correct_lines):
if test != correct:
print "Oh no! Expected %r; got %r." % (correct, test)
break
else:
len_diff = len(test_lines) - len(correct_lines)
if len_diff > 0:
print "Test file had too much data."
elif len_diff < 0:
print "Test file had too little data."
else:
print "Everything was correct!"
下面是使用Python difflib比較兩個文件的內容的一個簡單的例子...
import difflib
file1 = "myFile1.txt"
file2 = "myFile2.txt"
diff = difflib.ndiff(open(file1).readlines(),open(file2).readlines())
print ''.join(diff),
@OP:除了文檔,請看看Doug Hellmann出色的Python模塊difflib條目:http://blog.doughellmann.com/2007/10/pymotw- difflib.html – bernie 2009-06-10 20:11:39
@Adam - 感謝您的鏈接 - 我會檢查出來 – Triptych 2009-06-10 21:14:31
@bernie鏈接已死,您有更新的地址嗎? – BlackVegetable 2015-02-06 20:45:03