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

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

先上个图来看看效果:

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

#!/usr/bin/env python3

import difflib
import sys

try:
    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).

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

符号含义
-只包含于第一个文件
+只包含于第二个文件
^标示出现差异的字符
?不太明白这里的用法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值