自己动手做一个文本比较器

来源:互联网 发布:java从入门到精通txt 编辑:程序博客网 时间:2024/05/30 22:45

事情的起因是这样的:有两个.swift文件,它们的差别很小,但是我不想用眼睛去比较。以前在windows下用过盗版beyond compare,今天看书才发现python自带的difflib模块就可以做到。

先上个图来看看效果:

上面的效果是用difflib模块的HtmlDiff类实现的。HtmlDiff能将比较结果输出成html格式,如果用浏览器打开就是上图中的样子。

#!/usr/bin/env python3import difflibimport systry:    file1 = sys.argv[1]    file2 = sys.argv[2]except Exception as e:    print("Error: " + str(e))    sys.exit()def readfile(filename):    try:        fileHandle = open(filename, 'r')        text = fileHandle.read().splitlines() #使用行作为分割符        fileHandle.close()        return text    except IOError as error:        print('Read ' + filename + 'error: ' + str(error))        sys.exit()textOfFile1 = readfile(file1)textOfFile2 = readfile(file2)d = difflib.HtmlDiff() #创建HtmlDiff类的实例print(d.make_file(textOfFile1, textOfFile2))

使用时是这样的: $ python3 diff.py file1.txt file2.txt > haha.html // 结果存为haha.html, 方便用浏览器打开。

HtmlDiff 配合浏览器可以实现良好的视觉效果。difflib还有一个类Differ, 可以将比较结果输出为一个数组。将上面的代码修改一下:

# d = difflib.HtmlDiff()# print(d.make_file(textOfFile1, textOfFile2))d = difflib.Differ()diffContent = d.compare(textOfFile1, textOfFile2)print('\n'.join(list(diffContent))) #将list中的每个元素用'\n'连接起来,否则都输出到一行

输出:

MacBook-Pro:python Smith$ python3 diff.py file1.txt file2.txt   On Wednesday morning,   the premier treated the leaders, - many of whom are first-time visitors to China, ?                                              ^^+ many of whom are first-time visitors to China.?                                              ^- to ride on the world's fastest bullet train, from Suzhou, ? ^+ To ride on the world's fastest bullet train, from Suzhou, ? ^  Jiangsu province, to Shanghai. - The trip followed the conclusion of the Fourth ?                                         ^     -+ The trip followed the conclusion of the fourth?                                         ^+ Some other message.  Summit of China and Central and Eastern European Countries (16+1).

其中 “+, -, ?”的含义如下

符号 含义 - 只包含于第一个文件 + 只包含于第二个文件 ^ 标示出现差异的字符 ? 不太明白这里的用法
0 0
原创粉丝点击