- 在线时间
- 471 小时
- 最后登录
- 2025-8-11
- 注册时间
- 2023-7-11
- 听众数
- 4
- 收听数
- 0
- 能力
- 0 分
- 体力
- 7603 点
- 威望
- 0 点
- 阅读权限
- 255
- 积分
- 2861
- 相册
- 0
- 日志
- 0
- 记录
- 0
- 帖子
- 1160
- 主题
- 1175
- 精华
- 0
- 分享
- 0
- 好友
- 1
该用户从未签到
 |
- difflib是Python标准库中的一个模块,用于比较和处理文本之间的差异。它提供了一些函数和类,可以用于生成差异报告、计算相似度、查找最长公共子序列等操作。
安装内置库 无需安装常见用法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)
复制代码
输出,相似度 百分之63.6%0.6363636363636364常见用法5:获取两个字符串的相似块:- import difflib
- text1 = "hello world"
- text2 = "hello there"
- blocks = difflib.SequenceMatcher(None, text1, text2).get_matching_blocks()
- print(blocks)
复制代码
输出[Match(a=0, b=0, size=6), Match(a=8, b=9, size=1), Match(a=11, b=11, size=0)] - 常见用法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)
复制代码
|
zan
|