Loading

两个字符串的差异对比

本示例通过使用difflib模块实现两个字符串的差异对比,然后以版本控制风格进行输出。

#!/usr/bin/env python

import difflib

text1 = """text1:   #定义字符串1
This module provides classes and functions for comparing sequences.
including HTML and context and unified diffs.
difflib document v7.4
add string"""

text1_lines = text1.splitlines()                #以行进行分割,以便进行对比
text2 = """text2:           #定义字符串2
This module provides classes and functions for comparing sequences.
including HTML and context and unified diffs.
difflib document v7.5
add string"""

text2_lines = text2.splitlines()
d = difflib.Differ()            #创建Differ()对象
diff = d.compare(text1_lines,text2_lines)           #采用compare方法对字符串进行比较
print('\n'.join(list(diff)))

被示例采用Differ()类对两个字符串进行比较,另外difflib的SuquenceMatcher()类支持任意类型序列的比较,HtmlDiff()类支持将比较结果输出为HTML格式,示例运行结果如下:

[root@localhost diff_lib]# python3 simple1.py
- text1:   #定义字符串1
+ text2:           #定义字符串2
  This module provides classes and functions for comparing sequences.
  including HTML and context and unified diffs.
- difflib document v7.4
?                     ^

+ difflib document v7.5
?                     ^

  add string

符号含义说明:

符号 含义
'_' 包含在第一行序列行中,但不包含在第二行序列行
'+' 包含在第二行序列行中,但不包含在第一行序列行
'' 两个序列行一致
'?' 标志两个序列行存在增量差异
'^' 标志出两个序列行存在的差异字符

 

posted @ 2018-05-25 11:27  KubeSec  阅读(6239)  评论(0编辑  收藏  举报