python文本比较库difflib使用示例,pythondifflib,python的包很丰富,


python的包很丰富, difflib是用来做文本比较的,下面是一个使用例子:

import diffliblines1 = '''dogcatbirdbuffalogophershoundhorse'''.strip().splitlines()lines2 = '''catdogbirdbuffalogopherhorsemouse'''.strip().splitlines()# Changes:# swapped positions of cat and dog# changed gophers to gopher# removed hound# added mousefor line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm=''):    print line

输出内容如下:

Outputs the following:--- file1+++ file2@@ -1,7 +1,7 @@+cat dog-cat bird buffalo-gophers-hound+gopher horse+mouse

这个类库也可以用来比较两个文本文件。

评论关闭