前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python开发_difflib字符串比较

python开发_difflib字符串比较

作者头像
Hongten
发布2018-09-13 13:45:59
1.3K0
发布2018-09-13 13:45:59
举报
文章被收录于专栏:HongtenHongten

在python的difflib

HtmlDiff:比较后以html方法展示

我们比较的是字符串:

'hello world!' 和 'hElLO Wor2d!'

具体代码:

 1 from difflib import *
 2 import os
 3 
 4 def write():
 5      if os.path.exists('E:\\info.html'):
 6          with open('E:\\info.html','w+') as fp:
 7              test = HtmlDiff.make_file(HtmlDiff(), 'hello world!', 'hElLO Wor2d!')
 8              fp.write(test)
 9              print('生成文件成功!')
10              fp.close()
11              
12              
13 def main():
14     write()
15 
16 if __name__ == '__main__':
17     main()

differ

运行代码:

1 import difflib
2 
3 test = difflib.Differ().compare('hello world', 'HeLLO,wOrlD!')
4 print('横向展示:')
5 print(''.join(list(test)))
6 print('#' * 50)
7 test = difflib.Differ().compare('hello world', 'HeLLO,wOrlD!')
8 print('纵向展示:')
9 print('\n'.join(list(test)))

SquenceMatcher

运行代码:

 1 import difflib
 2 
 3 def test():
 4     test = difflib.SequenceMatcher(lambda x: x == " ", 'hello world', 'HeLLO,wOrlD!')
 5     for block in test.get_matching_blocks():
 6         print("a[%d] and b[%d] match for %d elements" % block)
 7 
 8 def main():
 9     test()
10 
11 if __name__ == '__main__':
12     main()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2013-08-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档