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将回车作为输入内容的实例

当input输入内容的时候,许多情况下输入回车键另起一行输入,但是这时候Pycharm就执行程序,然后结束,导致无法继续输入内容。 原因:Python默认遇到回车的时候,输入结束。所以我...

python 正则表达式参数替换实例详解

正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。 Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。 re 模块使...

Django xadmin开启搜索功能的实现

应用目录下adminx.py class EmailVerifyRecordAdmin(object): search_fields = ['code','email','sen...

Python多重继承的方法解析执行顺序实例分析

Python多重继承的方法解析执行顺序实例分析

本文实例讲述了Python多重继承的方法解析执行顺序。分享给大家供大家参考,具体如下: 任何实现多重继承的语言都要处理潜在的命名冲突, 这种冲突由不相关的祖先类实现同名方法引起 c...

Python实现字符串与数组相互转换功能示例

Python实现字符串与数组相互转换功能示例

本文实例讲述了Python实现字符串与数组相互转换功能。分享给大家供大家参考,具体如下: 字符串转数组 str = '1,2,3' arr = str.split(',') prin...