本文实例讲述了python实现比较两段文本不同之处的方法。分享给大家供大家参考。具体实现方法如下:
# find the difference between two texts# tested with python24 vegaseat 6/2/2005import difflibtext1 = the world's shortest books:human rights advances in chinamy plan to find the real killers by oj simpsonstrom thurmond: intelligent quotesamerica's most popular lawyerscareer opportunities for history majorsdifferent ways to spell bobdr. kevorkian's collection of motivational speechesspotted owl recipes by the epathe engineer's guide to fashionralph nader's list of pleasurestext2 = the world's shortest books:human rights advances in chinamy plan to find the real killers by oj simpsonstrom thurmond: intelligent quotesamerica's most popular lawyerscareer opportunities for history majorsdifferent ways to sell bobdr. kevorkian's collection of motivational speechesspotted owl recipes by the epathe engineer's guide to passionralph nader's list of pleasures# create a list of lines in text1text1lines = text1.splitlines(1)print lines of text1:for line in text1lines: print line,print# dito for text2text2lines = text2.splitlines(1)print lines of text2:for line in text2lines: print line,print diffinstance = difflib.differ()difflist = list(diffinstance.compare(text1lines, text2lines))print '-'*50print lines different in text1 from text2:for line in difflist: if line[0] == '-': print line,
希望本文所述对大家的python程序设计有所帮助。