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实现确认字符串是否包含指定字符串的实例

有时候我们需要在某段字符串或者某段语句中去查找确认是否包含我们所需要的字符串信息, 举例子说、 某段变量是:A= ”My name is Clay, and you can get my...

Python的高阶函数用法实例分析

本文实例讲述了Python的高阶函数用法。分享给大家供大家参考,具体如下: 高阶函数 1.MapReduce MapReduce主要应用于分布式中。 大数据实际上是在15年下半年开始火起...

flask-socketio实现WebSocket的方法

【flask-socektio】 之前不知道在哪个场合下提到过如何从web后台向前台推送消息。听闻了反向ajax技术这种模式之后,大呼神奇,试了一下之后发现也确实可以用。不过,反向aj...

初步介绍Python中的pydoc模块和distutils模块

pydoc Ka-Ping Yee 曾创建了一个相当著名的模块,名叫 pydoc (比较而言: pydoc 可以做到 perldoc 所能做的任何事,并且做得更好、更漂亮:-)。对于 P...

Python探索之创建二叉树

问题 创建一个二叉树 二叉树有限多个节点的集合,这个集合可能是: 空集 由一个根节点,和两棵互不相交的,分别称作左子树和右子树的二叉树组成 创建二叉树,创建节点,再创建节点之间...