3.3.3 Differ对象

Differ对象是进行全文比较,然后列表那一个位置增加、减少或者相同。

类difflib.Differ(linejunk=None, charjunk=None) 

构造一个Differ对象,linejunk和charjunk是可选的过滤函数,如果不设置,默认为None。

linejunk是一个可以过滤不需要的字符串行的函数对象,当不需要时返回True。

charjunk是一个可以过滤不需要的字符的函数对象,当不需要时返回True。

 

compare(a, b)

比较两个序列,生成一个增加或删除的文本描述。

3.3.4 使用Differ对象

Differ对象主要用来比较文本之间的差异,然后把差异文本按一定规则生成一个字符串返回。

比较两个简单的字符串

例子:
#python3.4.3
 
import difflib
from pprint import pprint
 
s1 = ' abcd 123 321'
s2 = 'abcd abcd 123321'
 
print('s1 = ', s1)
print('s2 = ', s2)
print('s1 == s2', s1 == s2)
print('')
 
diff = difflib.Differ()
print(diff)
l = list(diff.compare(s1, s2))
pprint(l)
结果输出如下:
s1 =   abcd 123 321
s2 =  abcd abcd 123321
s1 == s2 False
 
<difflib.Differ object at 0x0298B4D0>
['+ a',
 '+ b',
 '+ c',
 '+ d',
 '   ',
 '  a',
 '  b',
 '  c',
 '  d',
 '   ',
 '  1',
 '  2',
 '  3',
 '-  ',
 '  3',
 '  2',
 '  1']

从这个例了里可以看到,先创建Differ对象,然后调用函数compare来比较字符串s1和s2,最后把结果生成一个列表list返回,通过pprint来打印输出,这里使用pprint打印是由于这样输出更容易看得清楚,每一行是增加还是减少,是保持不变等等。结果里前面有加号表示增加,没有符号的是表示不变,减号表示删除。

 

多行文本进行比较

对于文本文件进行比较,在需要的应用场合还是比较多的,比如源码的版本控制里比较两个不同的版本的修改,这样可以知道每个版本变更了什么代码;比如在云服务里保存不同的文本时,是否只可以保留增加部分的数据,这样可以降低储存的成本,同时也可以恢复到以前的版本。

例子:

#python3.4.3
 
import difflib
from pprint import pprint
 
text1 = '''  1. Beautiful is better than ugly.
   2. Explicit is better than implicit.
   3. Simple is better than complex.
   4. Complex is better than complicated.
 '''.splitlines(keepends=True)
 
text2 = '''  1. Beautiful is better than ugly.
   3.   Simple is better than complex.
   4. Complicated is better than complex.
   5. Flat is better than nested.
 '''.splitlines(keepends=True)
 
diff = difflib.Differ()
print(diff)
l = list(diff.compare(text1, text2))
pprint(l)
结果输出如下:
<difflib.Differ object at 0x029EB4B0>
['    1. Beautiful is better than ugly.\n',
 '-    2. Explicit is better than implicit.\n',
 '-    3. Simple is better than complex.\n',
 '+    3.   Simple is better than complex.\n',
 '?      ++\n',
 '-    4. Complex is better than complicated.\n',
 '?             ^                     ---- ^\n',
 '+    4. Complicated is better than complex.\n',
 '?            ++++ ^                      ^\n',
 '+    5. Flat is better than nested.\n',
 '   ']

从结果看到这个显示更加详细很多,每一行里的字符差异都已经标记出来。