Python标准库--difflib模块

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('\n'.join(diff))

差异

diff2 = difflib.unified_diff(text1_lines, text2_lines, lineterm='')

print('\n'.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()获取将原列表变为新列表的操作指令

 

posted @ 2017-06-02 00:19  兔头咖啡  阅读(1511)  评论(0编辑  收藏  举报


作者:兔头咖啡
出处:http://www.cnblogs.com/wj5633/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。