python difflib详解_在 Python 中使用 difflib 比较字符串

本文介绍了如何使用Python的difflib模块来创建类似diff工具的功能,展示两个字符串之间的差异。同时,展示了如何忽略大小写、空白字符、制表符和换行符来比较两个字符串的相似性。示例代码分别演示了这两个功能的应用。
摘要由CSDN通过智能技术生成

用 Shell 写程序还是不方便,今天用 Python 把昨天写的 Bash 脚本重写了,遇到两个关于字符串的个小问题:

1、做个类似 diff 工具的效果,大致指出两个字符串的不同之处,这个可以用 difflib 模块解决。

!/usr/bin/python

import difflib

text1 = """http://www.vpsee.com is a website which is dedicated for

building scalable websites on cloud platforms. The keywords are: Linux, Mac,

Cloud Computing, C, Python, MySQL, Nginx, VPS, Performance, Scalability,

Architecture, ..., etc. Have fun!"""

text1_lines = text1.splitlines()

text2 = """http://VPSee.com is a website which is dedicated for

building scalable websites on cloud platforms. The keywords are: Linux, Mac,

Cloud Computing, C, Python, MySQL, Nginx, VPS, Performance, Scalability,

Programming, Optimisation, Architecture, ... , etc. Have fun !"""

text2_lines = text2.splitlines()

d = difflib.Differ()

diff = d.compare(text1_lines, text2_lines)

print '\n'.join(list(diff))

程序运行结果如下:

- http://www.vpsee.com is a website which is dedicated for

? ^^^^^^^

+ http://VPSee.com is a website which is dedicated for

? ^^^

building scalable websites on cloud platforms. The keywords are: Linux, Mac,

Cloud Computing, C, Python, MySQL, Nginx, VPS, Performance, Scalability,

- Architecture, ..., etc. Have fun!

+ Programming, Optimisation, Architecture, ... , etc. Have fun !

2、如何比较两个字符串,并且忽略大小写、空白字符、TAB 制表符、换行等。这个很容易解决,把字符串转换成小写后 split,然后以空格为分隔符 join 在一起。

#!/usr/bin/python

a = " \t\n\n a B C d\t\n\n\n"

b = "\t\t\n\n a b c D\n\n\n\n"

s1 = a.lower()

s1 = ' '.join(s1.split())

s2 = b.lower()

s2 = ' '.join(s2.split())

if s1 == s1:

print "=="

else:

print "!="

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值