![](/img/trans.png)
[英]Counting matches / Comparing two text files in python with utf-8 encoding
[英]Comparing two text files in python and counting the differences
嗨,我一直在嘗試比較 Python 中的兩個文本文件,基本上我想打開它們並一次比較一個字符,如果字符不同,則將 1 添加到計數器,然后顯示該值。
這是我到目前為止所擁有的:
#!/usr/bin/env python
diff = 0
import random
import string
import sys
file_A = sys.argv[1]
file_B = sys.argv[2]
read_A=open(file_A,'r').read()
read_B=open(file_B,'r').read()
for a in read_A:
for b in read_B:
if a != b:
diff = diff + 1
return diff
break
print "No of Differences ",diff
現在它確實計數,但它返回的值似乎不正確。
任何建議或幫助將不勝感激
最簡單的方法是使用difflib 。 它不需要任何額外的python雞蛋,並且可以很好地跟蹤各種diff檢查。 差異檢查的結果將是您期望檢查是否相等以及緊密匹配的結果。 如果允許對結果進行加權,那也可能很重要。
循環不一定是執行此操作的Python方法。 無需使用任何外部庫,就可以使用簡單的列表推導來查找兩個文件之間的差異實例:
如果順序很重要:
x=[i for i, j in zip(read_A, read_B) if i != j]
print len(x)
如果訂單不顯著:
x=[i in read_B for i in read_A]
#Now count the instances where the comparison resulted in False
i = x.count(False)
如果您有兩個要逐個字符比較的字符串,則最好壓縮它們。
因此,一旦執行此操作:
read_A=open(file_A,'r').read()
read_B=open(file_B,'r').read()
你做:
for char_a, char_b in zip(read_A, read_B):
if char_a != char_b:
# something
如果文件很大,您可能希望僅逐個字符地讀取字符,並使用izip
而不是zip
...
順便說一句...
您沒有關閉文件。 始終以這種方式訪問文件是一個好主意:
with open(file_A, 'r') as f1:
read_A = f1.read()
with open(file_B, 'r') as f2:
read_B = f2.read()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.