Python中的difflib库提供了比较文件或字符串差异的功能。除了基本的diff方法,它还提供了一些高级用法,如unified_diff、ndiff和HtmlDiff等。
示例代码:
import difflib
with open('file1.txt', 'r') as f1, open('file2.txt', 'r') as f2:
diff = list(difflib.unified_diff(f1.readlines(), f2.readlines()))
for line in diff:
print(line)
示例代码:
import difflib
seq1 = ['apple', 'banana', 'cherry']
seq2 = ['banana', 'cherry', 'date']
diff = list(difflib.ndiff(seq1, seq2))
for line in diff:
print(line)
示例代码:
import difflib
with open('file1.txt', 'r') as f1, open('file2.txt', 'r') as f2:
html_diff = difflib.HtmlDiff().make_file(f1.readlines(), f2.readlines())
with open('diff.html', 'w') as f:
f.write(html_diff)
这些高级用法可以帮助你更灵活地处理文本差异,满足不同场景下的需求。