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

相关文章

PyCharm代码提示忽略大小写设置方法

PyCharm代码提示忽略大小写设置方法

如图: 具体见上图! 以上这篇PyCharm代码提示忽略大小写设置方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。...

Python处理json字符串转化为字典的简单实现

今天一个朋友给个需求: 来来 {'isOK': 1, 'isRunning': None, 'isError': None} 怎么转换成字典 好,一看就是json转化很简单,开始:...

python实现对象列表根据某个属性排序的方法详解

本文实例讲述了python实现对象列表根据某个属性排序的方法。分享给大家供大家参考,具体如下: 对于一个已有的python list, 里面的内容是一些对象,这些对象有一些相同的属性值,...

python根据给定文件返回文件名和扩展名的方法

本文实例讲述了python根据给定文件返回文件名和扩展名的方法。分享给大家供大家参考。具体分析如下: 这段代码可以根据文件的完整路径返回文件名和扩展名,python的函数可以同时返回两个...

Python反射的用法实例分析

本文实例讲述了Python反射的用法。分享给大家供大家参考,具体如下: 在做程序开发中,我们常常会遇到这样的需求:需要执行对象里的某个方法,或需要调用对象中的某个变量,但是由于种种原因我...