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

相关文章

django 开发忘记密码通过邮箱找回功能示例

一、流程分析: 1.点击忘记密码====》forget.html页面,输入邮箱和验证码,发送验证链接网址的邮件====》发送成功,跳到send_success.html提示 2.到邮箱里...

python使用datetime模块计算各种时间间隔的方法

本文实例讲述了python使用datetime模块计算各种时间间隔的方法。分享给大家供大家参考。具体分析如下: python中通过datetime模块可以很方便的计算两个时间的差,dat...

Python中super关键字用法实例分析

本文实例讲述了Python中super关键字用法。分享给大家供大家参考。具体分析如下: 在Python类的方法(method)中,要调用父类的某个方法,在Python 2.2以前,通常的...

pyqt5 使用cv2 显示图片,摄像头的实例

如下所示: #! /usr/bin/python3 # coding = utf-8 # from PyQt5 import QtGui,QtCore,Qt import sys f...

python3 使用Opencv打开USB摄像头,配置1080P分辨率的操作

我就废话不多说了,直接上代码吧! import cv2 import time cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FR...