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遍历小写英文字母的方法

在c、c++等语言中,可以用字符+1的for循环来遍历小写的26个英文字母,但是由于python语言的特殊性,通过a + 1这种代码并不能成功遍历,以下是在python中遍历英文字母的简...

Django框架实现的分页demo示例

Django框架实现的分页demo示例

本文实例讲述了Django框架实现的分页。分享给大家供大家参考,具体如下: 首先初始化model,建表 class Book(models.Model): name = mode...

python高效过滤出文件夹下指定文件名结尾的文件实例

如下所示: import os def anyTrue(predicate, sequence): return True in map(predicate, sequence)...

Python实现字符串反转的常用方法分析【4种方法】

本文实例讲述了Python实现字符串反转的常用方法。分享给大家供大家参考,具体如下: 下面是实现python字符串反转的四种方法: 1. 切片 def rev(s): return...

Python xlwt设置excel单元格字体及格式

Python xlwt设置excel单元格字体及格式

本文根据自己初学经验编写的使用xlwt模块设置单元格的一些基本样式,如设置单元格的背景颜色,下框线,字体,字体的颜色,设置列宽行高,插入简单的图片,详细程序如下: #!/usr/bi...