Python 之 Difflib

2017年7月8日

word文档地址:https://wenku.baidu.com/view/36692440854769eae009581b6bd97f192379bf57

参考书籍:《Python自动化运维 ——技术与最佳实践》 作者:李天斯

1.什么是difflib

Difflib作为python的标准库,无需安装,作用是对比文本之间的差异,而且支持输出可读性比较强的HTML文档,与Linux下的vimdiff命令类似,我们可以比对文本、配置文件之间的差异,在版本控制方面非常有用。

2.difflib的简单使用

2.1 Differ的简单使用

2.1.1 编写python代码

 root@kali:/mnt/disk/python/difflib# cat difflib_0.py

 #!/usr/bin/env python

 import difflib

 text1 = '''

 I love HaiYan

 I very love HaiYan

 She's the one I love the most.

 '''

 text2 = '''

 I love LiWang

 I very love LiWang

 I'm his favorite person.

 '''

 d = difflib.Differ()

 print (list(d.compare(text1,text2)))

 

2.1.2 执行脚本输出

# python difflib_0.py

['  \n', '  I', '   ', '  l', '  o', '  v', '  e', '   ', '+ L', '- H', '- a', '  i', '- Y', '+ W', '  a', '  n', '+ g', '  \n', '  I', '   ', '  v', '  e', '  r', '  y', '   ', '  l', '  o', '  v', '  e', '   ', '+ L', '- H', '- a', '  i', '- Y', '+ W', '  a', '  n', '+ g', '  \n', '- S', '+ I', "+ '", '+ m', '+  ', '  h', '+ i', '- e', "- '", '  s', '   ', '+ f', '+ a', '+ v', '+ o', '+ r', '+ i', '  t', '- h', '  e', '   ', '+ p', '+ e', '+ r', '+ s', '  o', '  n', '- e', '-  ', '- I', '-  ', '- l', '- o', '- v', '- e', '-  ', '- t', '- h', '- e', '-  ', '- m', '- o', '- s', '- t', '  .', '  \n']

输出了看不懂的列表,打印列表后再进行查看

增加代码:

 list1 = list(d.compare(text1,text2))

 for line in list1:

     if line == "\n":

         print ("\n")

     print ("%s" %(line),end='')

执行代码:

# python3 difflib_0.py   

  I     l  o  v  e   + L- H- a  i- Y+ W  a  n+ g  

  I     v  e  r  y     l  o  v  e   + L- H- a  i- Y+ W  a  n+ g  

- S+ I+ '+ m+    h+ i- e- '  s   + f+ a+ v+ o+ r+ i  t- h  e   + p+ e+ r+ s  o  n- e-  - I-  - l- o- v- e-  - t- h- e-  - m- o- s- t  .

符号含义:

+:包含在第一个序列中,但不包含第二个序列

-:包含在第二个序列中,但是不包含第一个序列

 

2.2 HtmlDiff的简单使用

2.2.1 向文件写入内容

 # echo -e "I love HaiYan \nI very love HaiYan \nShe's the one I love the most." > test_1

 # echo -e "I love LiWang \nI very love LiWang \nI'm his favorite person" > test_2

2.2.2 编写python代码

 # cat  difflib_1.py

 #!/usr/bin/env python

 import difflib

 def open_files(filename):

    files = open(filename,'rb')

    text = files.read().splitlines()

    files.close()

    return text

 d = difflib.HtmlDiff()

 text_1 = open_files('test_1')

 text_2 = open_files('test_2')

 print (d.make_file(text_1,text_2))

2.2.3 执行脚本,用网页打开

 # python difflib_1.py > /mnt/disk/html/index.html

 

3.difflib案例

3.1 需求

需求:利用python实现一个功能,只需要执行[python脚本名称 文件1 文件2],只需要打开浏览器输入网址就能够看见文件比对效果

3.2 流程图

流程图:

3.3 代码编写:

 #cat difflib_2.py

 #!/usr/bin/env python

 #exit argv

 import sys

 #path

 import os

 #HtmlDiff

 import difflib

 html_files = '/mnt/disk/html/index.html'

 #Determine whether the parameter exists

 try:

     script_name = sys.argv[0]

     file1 = sys.argv[1]

     file2 = sys.argv[2]

 except:

     print ("%s Using: %s filename1 filename 2" %(script_name,script_name))

     sys.exit()

 #Function 1

 def dealwith_files(filename):

     #open files

     try:

         files = open(filename,'rb')

         #read files

         text = files.read().splitlines()

         #close files

         files.close()

     except:

         print ("Open files fail ")

         sys.exit()

     #return files

     return text

 #Determine if the files exists

 if os.path.isfile(file1) and os.path.isfile(file2):

     d = difflib.HtmlDiff()

     try:

         print_files = open(html_files,'w')

         print_files.write(d.make_file(dealwith_files(file1),dealwith_files(file2)))

         print_files.close()

     except:

         print ("write %s fail" %(html_files))

 #    print (d.make_file(dealwith_files(file1),dealwith_files(file2)))

 else:

     print ("%s or %s is not such file" %(file1,file2))

 sys.exit()

3.4 执行脚本输出

 #  difflib_2.py

 # ./difflib_2.py debconf.conf debconf.conf.bak

 #

chmod 是赋予脚本执行权限,执行difflib_2py 参数为debconf.conf debconf.conf.bak,没有任何输出,则证明执行OK

3.5 效果

刷新网页

Python 之 Difflib的更多相关文章

  1. python利用difflib判断两个字符串的相似度

    我们再工作中可能会遇到需要判断两个字符串有多少相似度的情况(比如抓取页面内容存入数据库,如果相似度大于70%则判定为同一片文章,则不录入数据库) 那这个时候,我们应该怎么判断呢? 不要着急,pytho ...

  2. 使用Python自带difflib模块进行文件内容差异对比

    difflib_text.py #!/usr/bin/python import difflib import sys try: textfile1=sys.argv[1] textfile2=sys ...

  3. Python Thrift 简单示例

    本文基于Thrift-0.10,使用Python实现服务器端,使用Java实现客户端,演示了Thrift RPC调用示例.Java客户端提供两个字符串参数,Python服务器端计算这两个字符串的相似度 ...

  4. 使用python比较两个文件的不同之处

    比较两个文件的不同之处用处还是比较大的,特别是比较两个版本的不同之处 [root@localhost python]# cat diftest.py #!/usr/bin/python import ...

  5. python开发_difflib字符串比较

    在python的difflib中 HtmlDiff:比较后以html方法展示 我们比较的是字符串: 'hello world!' 和 'hElLO Wor2d!' 具体代码: from difflib ...

  6. Python比较配置文件

    工作中最常见的配置文件有四种:普通key=value的配置文件.Json格式的配置文件.HTML格式的配置文件以及YAML配置文件. 这其中以第一种居多,后三种在成熟的开源产品中较为常见,本文只针对第 ...

  7. 你可能不知道的 Python 技巧

    英文 | Python Tips and Trick, You Haven't Already Seen 原作 | Martin Heinz (https://martinheinz.dev) 译者 ...

  8. difflib模块详解

    1.两个字符串对比 import difflib text1=""" test1 #定义字符串 hellow my name is machanwei! difflib ...

  9. 对比Nginx配置文件差异

    一.概要: Python2 官方文档:https://docs.python.org/2/library/difflib.html Python2 官方文档:https://docs.python.o ...

随机推荐

  1. 关于vue搭建项目运行出行的错误问题,简直是大坑啊

    解决方法简单粗暴,非常简单粗暴 直接在根目录新建一个test文件夹就可以搞定,用来放置配置文件的 折腾了我一上午啊

  2. 定时器NSTimer

    /** 添加定时器 */@property (nonatomic, strong) NSTimer *timer; - (void)addTimer{ // 2秒后,自己 调用nextImage方法 ...

  3. 详解Cookie纪要

    参考文档链接:http://mp.weixin.qq.com/s?__biz=MzAxODE2MjM1MA==&mid=2651552892&idx=1&sn=126a1d32 ...

  4. cookie session ORM 操作

    . ORM增删改查操作 http://www.cnblogs.com/liwenzhou/p/8660826.html . 单表增删改查 . 单表的双下划线操作 . 外键的跨表查询 . 正向查询 . ...

  5. PAT 1066 图像过滤(15)(代码)

    1066 图像过滤(15 分) 图像过滤是把图像中不重要的像素都染成背景色,使得重要部分被凸显出来.现给定一幅黑白图像,要求你将灰度值位于某指定区间内的所有像素颜色都用一种指定的颜色替换. 输入格式: ...

  6. Android.Tools.Eclipse hangs at the Android SDK Content Loader

    Eclipse hangs at the Android SDK Content Loader http://stackoverflow.com/questions/13489141/eclipse- ...

  7. linux下svn导入新目录到svn服务器特定地址

    svn import transplant-apps/ svn://xx.xx.xx.90/ -m "changelog:add transplant-apps to 90-svn" ...

  8. python连接Linux服务器

    import paramikoimport os #当前脚本路径CUR_PATH = os.path.dirname(__file__) #服务器ipHost=''Port=22#登录用户名Usern ...

  9. linux 和 主机通信的另类方法

    偶然发现,linux可以从github上直接下载代码.这样就能用windows写好代码,直接给linux来跑了.很方便. 当然是因为我还不会配置网络来让linux和windows通信.弄了一个下午也没 ...

  10. win7 64位远程连接oracle11g64位

    1.首先下载即时客户端 instantclient-basic-windows.x64-11.2.0.4.0,下载地址:http://www.oracle.com/technetwork/topics ...