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机器学习理论与实战(二)决策树

python机器学习理论与实战(二)决策树

        决策树也是有监督机器学习方法。 电影《无耻混蛋》里有一幕游戏,在德军小酒馆里有几个人在玩20问题游戏...

python绘制多个子图的实例

python绘制多个子图的实例

绘制八个子图 import matplotlib.pyplot as plt fig = plt.figure() shape=['.','o','v','>','<...

Python求导数的方法

本文实例讲述了Python求导数的方法。分享给大家供大家参考。具体实现方法如下: def func(coeff): sum='' for key in coeff:...

django 多对多表的创建和插入代码实现

这篇文章主要介绍了django-多对多表的创建和插入代码实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 表的创建 # 作者和书...

详解Python3 pandas.merge用法

详解Python3 pandas.merge用法

摘要 数据分析与建模的时候大部分时间在数据准备上,包括对数据的加载、清理、转换以及重塑。pandas提供了一组高级的、灵活的、高效的核心函数,能够轻松的将数据规整化。这节主要对panda...