difflib Compares Text With Unified Diffs
Compare expected versus actual text with difflib: unified_diff prints review-style diffs, SequenceMatcher scores similarity, get_close_matches suggests keys.
Code
import difflib
# unified_diff 是评审格式的差异输出:期望在前,实际在后
expected = ["timeout=30", "retries=3", "endpoint=/v2/orders"]
actual = ["timeout=45", "retries=3", "endpoint=/v2/orders"]
for line in difflib.unified_diff(expected, actual, fromfile="expected", tofile="actual", lineterm=""):
print(line)
# SequenceMatcher 用相似度定量两个序列的接近程度
ratio = difflib.SequenceMatcher(None, expected, actual).ratio()
print(f"similarity: {ratio:.3f}")
# get_close_matches 给拼写错误推荐最接近的已知键
known = ["timeout", "retries", "endpoint", "verbose"]
print("did you mean:", difflib.get_close_matches("rtries", known, n=2, cutoff=0.6))Where the work happens
Iteration happens inside for line in difflib.unified_diff(expected, actual, fromfile="expected", tofile="actual", lineterm… — everything outside it runs once.
The file’s state is a handful of top-level bindings: expected, actual, ratio, known.
What to watch for
- Requires
difflibas a package; the snippet will not run without it.
Applying it
The demo output is labeled (similarity:, did you mean:), so every printed line maps back to its originating operation.
Interactive Tools for This Topic
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. Every import resolves inside the standard library — `difflib`. Its state lives in module-level bindings: `expected`, `actual`, `ratio`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.