实现说明
文件的主干是一个循环——for tag, i1, i2, j1, j2 in matcher.get_opcodes()。
演示用的数据放在这几个模块级绑定中:old、new、old_words、new_words。
使用要点
- 每一步打印都带着自己的标签:
keep、swap、drop。
常见问题
这份代码可以原样复制进项目使用吗?
可以。粘进去就能运行,中间没有包管理器的事。 全部导入都来自标准库:difflib。 跨调用保留的状态放在这些顶层绑定里:old、new、old_words。
核心语句
elif tag == 'replace':
print(f'swap {old_words[i1:i2]} -> {new_words[j1:j2]}')
elif tag == 'delete':
print(f'drop {old_words[i1:i2]}')
代码示例
import difflib
old = 'the deploy finished without any error today'
new = 'the deploy finished without a single error today'
# Split into words first, so opcodes describe sentence edits
# instead of whole-line replacements
old_words = old.split()
new_words = new.split()
matcher = difflib.SequenceMatcher(None, old_words, new_words)
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
if tag == 'equal':
print(f'keep {old_words[i1:i2]}')
elif tag == 'replace':
print(f'swap {old_words[i1:i2]} -> {new_words[j1:j2]}')
elif tag == 'delete':
print(f'drop {old_words[i1:i2]}')
else:
print(f'insert {new_words[j1:j2]}')