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

相关文章

将pandas.dataframe的数据写入到文件中的方法

将pandas.dataframe的数据写入到文件中的方法

导入实验常用的python包。如图2所示。 【import pandas as pd】pandas用来做数据处理。【import numpy as np】numpy用来做高维度矩阵运算....

python实现栅栏加解密 支持密钥加密

python实现栅栏加解密 支持密钥加密

栅栏加解密是对较短字符串的一种处理方式,给定行数Row,根据字符串长度计算出列数Column,构成一个方阵。 加密过程:就是按列依次从上到下对明文进行排列,然后按照密钥对各行进行打乱,最...

pytorch实现用CNN和LSTM对文本进行分类方式

model.py: #!/usr/bin/python # -*- coding: utf-8 -*- import torch from torch import nn imp...

Python编写电话薄实现增删改查功能

初学python,写一个小程序练习一下。主要功能就是增删改查的一些功能。主要用到的技术:字典的使用,pickle的使用,io文件操作。代码如下: import pickle #s...

Python科学计算环境推荐——Anaconda

Python科学计算环境推荐——Anaconda

Anaconda是一个和Canopy类似的科学计算环境,但用起来更加方便。自带的包管理器conda也很强大。 首先是下载安装。Anaconda提供了Python2.7和Python3.4...