Perbedaan Teks
Bandingkan dua teks baris per baris dan sorot penambahan, penghapusan, dan baris yang tidak berubah.
Pertanyaan yang Sering Diajukan
Implementasi Kode
import difflib
def line_diff(original: str, modified: str) -> list[str]:
"""Return unified diff lines between two multi-line strings."""
orig_lines = original.splitlines(keepends=True)
mod_lines = modified.splitlines(keepends=True)
return list(difflib.unified_diff(
orig_lines, mod_lines,
fromfile="original", tofile="modified",
lineterm=""
))
def side_by_side_diff(original: str, modified: str):
"""Yield (tag, line_a, line_b) tuples for a side-by-side view."""
matcher = difflib.SequenceMatcher(None, original.splitlines(), modified.splitlines())
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
orig_block = original.splitlines()[i1:i2]
mod_block = modified.splitlines()[j1:j2]
max_len = max(len(orig_block), len(mod_block))
for k in range(max_len):
a = orig_block[k] if k < len(orig_block) else ""
b = mod_block[k] if k < len(mod_block) else ""
yield tag, a, b
# Example
text_a = """apple
banana
cherry"""
text_b = """apple
blueberry
cherry
date"""
# Unified diff
for line in line_diff(text_a, text_b):
print(line)
# Side-by-side
print("\n--- Side by side ---")
for tag, a, b in side_by_side_diff(text_a, text_b):
marker = " " if tag == "equal" else ("+" if tag == "insert" else ("-" if tag == "delete" else "~"))
print(f"{marker} {a!r:20} | {b!r}")Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.