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. Head First Servlets & JSP 学习笔记 第五章 —— 作为Web应用

    初始化参数:(init-param) 初始化参数写在web.xml文件中:(写在<servlet>标签内部) <servlet> <servlet-name>Bee ...

  2. node.js中对同步,异步,阻塞与非阻塞的理解

    我们都知道javascript是单线程的,node.js是一个基于Chrome V8 引擎的 javascript 运行时环境,注意 node.js 不是一门语言,别搞错了. javascript为什 ...

  3. EntityFramework的linq扩展where

    代码 using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; ...

  4. 6.MySQL图形化工具的使用

    6.图形化工具的使用6.1 Mysql Workbench Mysql Workbench是Mysql官方推出的集成图形化工具,替代了之前的图形化管理工具Mysql Administrator和图形化 ...

  5. ssm介绍

    1.Spring     Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE ...

  6. 虚拟机安装centos7, 再安装gitlab 简单步骤

    先安装Linux centos7(朋友贡献的. Linux官网有下) 我自己用vm安装的. 未出现特殊状况 gitlab的搭建 安装基础包 yum -y install curl policycore ...

  7. 0 or 1,1 and 0

    最近小编遇到很头疼的的一件事 就是以下这几道运算题 ,以下结果是小编经过大量的运算得出的 一.或运算 1.0 or 1 结果为:1 2.1 or 0 结果为:1 3.1 or 2 结果为:1 4.2 ...

  8. Python GUI中 text框里实时输出

    首先GUI中不同函数的局部变量的问题. 发现不同button定义的函数得到的变量无法通用. 通过global 函数内的变量可以解决这个问题 def openfiles2(): global s2fna ...

  9. android xml 解析汉字只出来一个字的问题

    DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); // 实例化DocumentBuilder factor ...

  10. 脚本路径问题_dirname

    pwd可获取命令当前的路径 可是若我们想在脚本中获取脚本所在文件夹的路径,这种方法是不够用的. 例如,我们的脚本放在/home/user/script/下,名字叫做getpath.sh getpath ...