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

相关文章

利用python发送和接收邮件

利用python发送和接收邮件

关于电子邮件  大学之前,基本不用邮箱,所以基本感觉不到它的存在,也不知道有什么用;然而大学之后,随着认识的人越来越多,知识越来越广泛,邮箱已然成为很重要的通讯工具,大学一些...

opencv-python 提取sift特征并匹配的实例

我就废话不多说,直接上代码吧! # -*- coding: utf-8 -*- import cv2 import numpy as np from find_obj import...

python3下实现搜狗AI API的代码示例

1、背景 a、搜狗也发布了自己的人工智能 api,包括身份证ocr、名片ocr、文本翻译等API,初试感觉准确率一般般。 b、基于python3。 c、也有自己的签名生成这块,有了鹅厂的...

2款Python内存检测工具介绍和使用方法

去年自己写过一个程序时,不太确定自己的内存使用量,就想找写工具来打印程序或函数的内存使用量。这里将上次找到的2个内存检测工具的基本用法记录一下,今后分析Python程序内存使用量时也是需...

浅谈Python的垃圾回收机制

一.垃圾回收机制 Python中的垃圾回收是以引用计数为主,分代收集为辅。引用计数的缺陷是循环引用的问题。 在Python中,如果一个对象的引用数为0,Python虚拟机就会回收这个对象...