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打开文件、文件读写操作、with方式、文件常用函数实例分析

Python打开文件、文件读写操作、with方式、文件常用函数实例分析

本文实例讲述了Python打开文件、文件读写操作、with方式、文件常用函数。分享给大家供大家参考,具体如下: 打开文件: 在python3中,打开文件的函数是: open(file,...

Python 调用 zabbix api的方法示例

前提准备: 1.使用python requests模块 2.了解json 3.zabbix api的具体调用建议先浏览一下官网 先上代码: import requests,json...

Python3 执行Linux Bash命令的方法

和之前C++执行Linux Bash命令的方法 一样,Python依然支持system调用和popen()函数来执行linux bash命令。 方法一:system调用 #仅仅在一个...

Python基于xlrd模块操作Excel的方法示例

本文实例讲述了Python基于xlrd模块操作Excel的方法。分享给大家供大家参考,具体如下: 一、使用xlrd读取excel 1、xlrd的安装: pip install xlr...

python之wxPython应用实例

python之wxPython应用实例

本文实例讲述了python之wxPython的使用方法,分享给大家供大家参考。具体方法如下: 先来看看效果,这里加载一张图片: 代码如下: #!/usr/bin/env pytho...