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图形用户接口实例的具体代码,供大家参考,具体内容如下 运用tkinter图形库,模拟聊天应用界面,实现信息发送. from tkinter impor...

Python异常模块traceback用法实例分析

本文实例讲述了Python异常模块traceback用法。分享给大家供大家参考,具体如下: traceback模块被用来跟踪异常返回信息. 如下例所示: import traceba...

python在linux系统下获取系统内存使用情况的方法

本文实例讲述了python在linux系统下获取系统内存使用情况的方法。分享给大家供大家参考。具体如下: """ Simple module for getting amount o...

详解Python的Lambda函数与排序

lambda函数是一种快速定义单行的最小函数,是从 Lisp 借用来的,可以用在任何需要函数的地方。下面的例子比较了传统的函数与lambda函数的定义方式。 前几天看到了一行求1000...

Python json模块使用实例

实际上JSON就是Python字典的字符串表示,但是字典作为一个复杂对象是无法直接传递,所以需要将其转换成字符串形式.转换的过程也是一种序列化过程. 用json.dumps序列化为jso...