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实现按长宽比缩放图片

使用python按图片固定长宽比缩放图片到指定图片大小,空白部分填充为黑色。 代码 # -*- coding: utf-8 -*- from PIL import Image c...

对python条件表达式的四种实现方法小结

如下所示: a, b, c = 1, 2, 3   # 1.常规   if a>b:     c...

python socket网络编程之粘包问题详解

python socket网络编程之粘包问题详解

一,粘包问题详情 1,只有TCP有粘包现象,UDP永远不会粘包 你的程序实际上无权直接操作网卡的,你操作网卡都是通过操作系统给用户程序暴露出来的接口,那每次你的程序要给远程发数据时,...

CentOS7下安装python3.6.8的教程详解

CentOS7下安装python3.6.8的教程详解

由于最近有个任务需要在python环境下跑,项目是python3.6 + tensorflow1.3.1.现总结安装环境: 卸载Python3.6方法: 首先用命令: whereis...

在pycharm中python切换解释器失败的解决方法

在pycharm中python切换解释器失败的解决方法

在pycharm中我们有时需要切换python的版本,这里需要注意的是我们是在PyCharm中的Preferences中切换的, 在File的Setting中切换可能会导致失败 以上...