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

Posted in 未分类

发表评论