一 点睛
本篇介绍如何通过difflib模块实现文件内容差异对比。difflib作为 Python的标准库模块,无需安装,作用是对比文本之间的差异,且支持输出可读性比较强的HTML文档,与Linux下的diff命令相似。我们可以使用difflib对比代码、配置文件的差别,在版本控制方面是非常有用。 Python 2.3或更高版本默认自带difflib模块,无需额外安装。
二 两个字符串的差异对比
1 点睛
本例通过使用difflib模块实现两个字符串的差异对比,然后以版本控制风格进行输出。
2 代码 ————————————————
代码语言:javascript复制#!/usr/bin/python
import difflib
text1 = """
text1:
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:
This module provides classes and functions for Comparing sequences.
including HTML and context and unified diffs.
difflib document v7.5"""
text2_lines = text2.splitlines()
d = difflib.Differ()
diff = d.compare(text1_lines, text2_lines)
print ('n'.join(list(diff)))
结果
代码语言:javascript复制E:Pythonpython_auto_maintainvenvScriptspython.exe E:/Python/python_auto_maintain/2_1_1.py
- text1:
? ^
text2:
? ^
- This module provides classes and functions for comparing sequences.
? ^
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
说明
采用Differ()类对两个字符串进行比较,另外difflib的 SequenceMatcher()类支持任意类型序列的比较,HtmlDiff()类支持将比较结果输出为HTML格式。