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

yipeiwu_com6年前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 二分查找和快速排序实例详解

思想简单,细节颇多;本以为很简单的两个小程序,写起来发现bug频出,留此纪念。 #usr/bin/env python def binary_search(lst,t): low...

wxPython绘图模块wxPyPlot实现数据可视化

wxPython绘图模块wxPyPlot实现数据可视化

本文实例为大家分享了wxPython绘图模块wxPyPlot实现数据可视化的具体代码,供大家参考,具体内容如下 #-*- coding: utf-8 -*- #########...

python print输出延时,让其立刻输出的方法

一句print("ni hao"),很久看不见,怎么让python print能立刻输出呢。 因为python默认是写入stdout缓冲的,使用-u参数启动python,就会立刻输出了。...

numpy中实现ndarray数组返回符合特定条件的索引方法

numpy中实现ndarray数组返回符合特定条件的索引方法

在numpy的ndarray类型中,似乎没有直接返回特定索引的方法,我只找到了where函数,但是where函数对于寻找某个特定值对应的索引很有用,对于返回一定区间内值的索引不是很有效,...

Python利用ElementTree模块处理XML的方法详解

前言 最近因为工作的需要,在使用 Python 来发送 SOAP 请求以测试 Web Service 的性能,由于 SOAP 是基于 XML 的,故免不了需要使用 python 来处理...