python实现比较两段文本不同之处的方法

yipeiwu_com5年前Python基础

本文实例讲述了python实现比较两段文本不同之处的方法。分享给大家供大家参考。具体实现方法如下:

# find the difference between two texts
# tested with Python24  vegaseat 6/2/2005
import difflib
text1 = """The World's Shortest Books:
Human Rights Advances in China
"My Plan to Find the Real Killers" by OJ Simpson
"Strom Thurmond: Intelligent Quotes"
America's Most Popular Lawyers
Career Opportunities for History Majors
Different Ways to Spell "Bob"
Dr. Kevorkian's Collection of Motivational Speeches
Spotted Owl Recipes by the EPA
The Engineer's Guide to Fashion
Ralph Nader's List of Pleasures
"""
text2 = """The World's Shortest Books:
Human Rights Advances in China
"My Plan to Find the Real Killers" by OJ Simpson
"Strom Thurmond: Intelligent Quotes"
America's Most Popular Lawyers
Career Opportunities for History Majors
Different Ways to Sell "Bob"
Dr. Kevorkian's Collection of Motivational Speeches
Spotted Owl Recipes by the EPA
The Engineer's Guide to Passion
Ralph Nader's List of Pleasures
"""
# create a list of lines in text1
text1Lines = text1.splitlines(1)
print "Lines of text1:"
for line in text1Lines:
 print line,
print
# dito for text2
text2Lines = text2.splitlines(1)
print "Lines of text2:"
for line in text2Lines:
 print line,
print 
diffInstance = difflib.Differ()
diffList = list(diffInstance.compare(text1Lines, text2Lines))
print '-'*50
print "Lines different in text1 from text2:"
for line in diffList:
 if line[0] == '-':
  print line,

希望本文所述对大家的Python程序设计有所帮助。

相关文章

用Python下载一个网页保存为本地的HTML文件实例

用Python下载一个网页保存为本地的HTML文件实例

我们可以用Python来将一个网页保存为本地的HTML文件,这需要用到urllib库。 比如我们要下载山东大学新闻网的一个页面,该网页如下: 实现代码如下: import urll...

Python基础之变量基本用法与进阶详解

Python基础之变量基本用法与进阶详解

本文实例讲述了Python基础之变量基本用法与进阶。分享给大家供大家参考,具体如下: 目标 变量的引用 可变和不可变类型 局部变量和全局变量 01. 变量的引用 变...

详解Python并发编程之创建多线程的几种方法

大家好,并发编程 今天开始进入第二篇。 今天的内容会比较基础,主要是为了让新手也能无障碍地阅读,所以还是要再巩固下基础。学完了基础,你们也就能很顺畅地跟着我的思路理解以后的文章。 本文...

用python登录Dr.com思路以及代码分享

前提:isp得支持web登录的方式。 说明:每个ISP的登录页面不一样,不过我估计算法都是一样的,于是解决方案应该也是相似的,只是表单的key可能不太一样。 首先,分析登录页面。 页面h...

使用PyQtGraph绘制精美的股票行情K线图的示例代码

使用PyQtGraph绘制精美的股票行情K线图的示例代码

pyqtgraph是Python平台上一种功能强大的2D/3D绘图库,相对于matplotlib库,由于其在内部实现方式上,使用了高速计算的numpy信号处理库以及Qt的Graphics...