python标准库(可在算法比赛使用的库)——difflib库

1.比较差异:

import difflib
​
text1 = "hello world"
text2 = "hello there"
​
diff = difflib.ndiff(text1, text2)
print('\n'.join(diff))

2.比较文件的差异

import difflib
​
with open('file1.txt') as file1, open('file2.txt') as file2:
    diff = difflib.ndiff(file1.readlines(), file2.readlines())
    print('\n'.join(diff))

3.比较列表的差异;

import difflib
​
list1 = ['apple', 'banana', 'cherry']
list2 = ['apple', 'banana', 'kiwi']
​
diff = difflib.ndiff(list1, list2)
print('\n'.join(diff))

4.比较字符串相似度:

import difflib
​
text1 = "hello world"
text2 = "hello there"
​
similarity = difflib.SequenceMatcher(None, text1, text2).ratio()
print(similarity)

5.获取两个字符串的相似块:

import difflib
​
text1 = "hello world"
text2 = "hello there"
​
blocks = difflib.SequenceMatcher(None, text1, text2).get_matching_blocks()
print(blocks)

6.获取两个字符串的最长公共子序列:

import difflib
​
text1 = "hello world"
text2 = "hello there"
​
lcs = difflib.SequenceMatcher(None, text1, text2).find_longest_match(0, len(text1), 0, len(text2))
print(lcs)

Match(a=0, b=0, size=6)

import difflib
​
text1 = "hello world"
text2 = "hello there"
​
lcs = difflib.SequenceMatcher(None, text1, text2).find_longest_match(0, len(text1), 0, len(text2))
print(text1[lcs.a: lcs.a + lcs.size])

hello

7.比较两个字符串,并返回上下文差异

import difflib
​
text1 = "hello world"
text2 = "hello there"
​
diff = difflib.context_diff(text1, text2)
print('\n'.join(diff))
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值