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并安装的步骤详解

下载官网python并安装的步骤详解

怎么下载官网python并安装? Python火了起来,很多人开始学习起来了,那么Python安装包,去哪里下载呢。那当然是去官网咯。 Python官网或直接 访问 https://ww...

Python超越函数积分运算以及绘图实现代码

Python超越函数积分运算以及绘图实现代码

编译环境:ubuntu17.04 Python3.5 所需库:numpy、scipy、matplotlib 下面是理想平面的辐射强度计算(课程大作业~~~) 1、超越函数积分运算 d...

解决python selenium3启动不了firefox的问题

解决python selenium3启动不了firefox的问题

selenium3.0之后的版本的就不支持直接打开火狐浏览器,启动火狐浏览器报错,如下图,要想运行就需要我们单独装上驱动。 3.0之前的版本,是可以直接打开火狐浏览器的。 解决办法:...

win10 64bit下python NLTK安装教程

win10 64bit下python NLTK安装教程

由于最近需要做项目,需要进行分词等,查了资料之后,发现python NLTK很强大,于是就想试试看。在网上找了很多安装资料,都不太完整,下载的时候也总是会出现一点小意外,最后终于也安装成...

Python生成器generator用法示例

Python生成器generator用法示例

本文实例分析了Python生成器generator用法。分享给大家供大家参考,具体如下: 生成器generator本质是一个函数,它记住上一次在函数体中的位置,在生成器函数下一次调用,会...