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 实现12bit灰度图像映射到8bit显示的方法

图像显示和打印面临的一个问题是:图像的亮度和对比度能否充分突出关键部分。这里所指的“关键部分”在 CT 里的例子有软组织、骨头、脑组织、肺、腹部等等。 技术问题 1、显示器往往只有 8-...

python实现的简单RPG游戏流程实例

本文实例讲述了python实现的简单RPG游戏流程。分享给大家供大家参考。具体如下: #RPG rpg = True whp = 100 mahp = 100 hhp = 100 M...

巧用Python装饰器 免去调用父类构造函数的麻烦

先看一段代码: 复制代码 代码如下: class T1(threading.Thread): def __init__(self, a, b, c): super(T1, self)._...

Python中处理字符串的相关的len()方法的使用简介

 len()方法返回字符串的长度。 语法 以下是len()方法的语法: len( str ) 参数     NA 返回值 此方法...

Python3实现带附件的定时发送邮件功能

本文实例为大家分享了Python3定时发送邮件功能的具体代码,供大家参考,具体内容如下 1、 导入模块 import os import datetime #定时发送,以及日期 i...