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

相关文章

一个基于flask的web应用诞生 组织结构调整(7)

一个基于flask的web应用诞生 组织结构调整(7)

现在所有的Py代码均写在default.py文件中,很明显这种方法下,一旦程序变的负责,那么无论对于开发和维护来说,都会带来很多问题。 Flask框架并不强制要求项目使用特定的组织结构,...

Python人脸识别第三方库face_recognition接口说明文档

1. 查找图像中出现的人脸 代码示例: #导入face_recognition模块 import face_recognition #将jpg文件加载到numpy数组中...

Python操作json的方法实例分析

Python操作json的方法实例分析

本文实例讲述了Python操作json的方法。分享给大家供大家参考,具体如下: python中对json操作方法有两种,解码loads()和编码dumps() 简单来说: impor...

python utc datetime转换为时间戳的方法

最近python代码遇到了一个神奇的需求, 就是如果将python utc datetime转换为时间戳. 百度找到都是使用time.mktime(xxx) 但是看到官网文档里写 t...

Django框架中方法的访问和查找

在 Django 模板中遍历复杂数据结构的关键是句点字符 (.)。 最好是用几个例子来说明一下。 比如,假设你要向模板传递一个 Python 字典。 要通过字典键访问该字典的值,可使用一...