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程序设计有所帮助。

相关文章

pycharm设置鼠标悬停查看方法设置

pycharm设置鼠标悬停查看方法设置

我们使用pycharm的时候,有时遇到了不认识的方法习惯于将鼠标悬停在方法上查看方法介绍。那么如何设置呢?下面小编给大家分享一下。 首先假如我们要查看下图所示的方法,鼠标放上去并没有显示...

numpy使用fromstring创建矩阵的实例

使用字符串创建矩阵是一个很实用的功能,之前自己尝试了很多次的小功能使用这个方法就能够简单实现。 创建长度为16的字符串,是为了方便能够在各种数据类型之间转换。 >>>...

Python实例之wxpython中Frame使用方法

本节为大家分享的例子是wxpython Frame的用法。 例子: 复制代码 代码如下:#!/usr/bin/python  # -*- coding: GBK -*-&nb...

python实现分页效果

python实现分页效果

本文实例为大家分享了python实现分页效果展示的具体代码,供大家参考,具体内容如下 难点:清空Layout #!/usr/bin/python #-*-coding:utf-...

Python3中使用PyMongo的方法详解

前言 本文主要给大家介绍的是关于在Python3使用PyMongo的方法,分享出来供大家参考学习,下面话不多说了,来一起看看详细介绍: MongoDB存储 在这里我们来看一下Python...