difflib:文本比较
text1 = """ wqrrytuerwhjh dsfghjjhhfgdfdsa xcvbnbnbcvcbn qqqqqqqqq """ text1_lines = text1.splitlines() text2 = """ wqrrytuerwhjh dsfghjjhhfgdfdsa xcvbnbnbcvcbn aaaaaaaaaa """ text2_lines = text2.splitlines() d = difflib.Differ() diff = d.compare(text1_lines, text2_lines) print(' '.join(diff))
差异
diff2 = difflib.unified_diff(text1_lines, text2_lines, lineterm='') print(' '.join(list(diff2))) """ --- +++ @@ -2,4 +2,4 @@ wqrrytuerwhjh dsfghjjhhfgdfdsa xcvbnbnbcvcbn -qqqqqqqqq +aaaaaaaaaa """
比较任意类型
from difflib import SequenceMatcher s1 = [1, 2, 3, 4, 5, 6] s2 = [2, 3, 5, 4, 6, 1] print('s1==s2:', s1 == s2) print() match = difflib.SequenceMatcher(None, s1, s2) print(match.get_opcodes()) """ s1==s2: False [('delete', 0, 1, 0, 0), ('equal', 1, 3, 0, 2), ('insert', 3, 3, 2, 3), ('equal', 3, 4, 3, 4), ('delete', 4, 5, 4, 4), ('equal', 5, 6, 4, 5), ('insert', 6, 6, 5, 6)] """
match.get_opcodes()获取将原列表变为新列表的操作指令