Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Helpers for Computing Deltas ใน Python (โมดูล difflib)

โมดูล difflib ให้ Classes/Functions สำหรับเปรียบเทียบ Sequences (Strings, Lines, Files) และสร้าง Diff/Delta

import difflib


Class: SequenceMatcher

เปรียบเทียบ 2 Sequences ใดๆ (ไม่ใช่แค่ Text)

เมธอดหลัก

Methodคำอธิบาย
set_seqs(a, b)ตั้งค่า Sequences ทั้งคู่
set_seq1(a) / set_seq2(b)ตั้งค่า Sequence เดี่ยว
find_longest_match(alo, ahi, blo, bhi)หา Matching Block ยาวสุดใน Range
get_matching_blocks()List ของ Matching Blocks (Descending Size)
get_opcodes()List Operations: replace, delete, insert, equal
ratio()Similarity Ratio (0.0 - 1.0)
quick_ratio()ประมาณ Ratio เร็วกว่า
real_quick_ratio()ประมาณ Ratio เร็วที่สุด

โค้ดตัวอย่าง

import difflib

s1 = 'Python Programming'
s2 = 'Python Standard Library'

sm = difflib.SequenceMatcher(None, s1, s2)
print(f"Ratio: {sm.ratio():.3f}")  # 0.488

for block in sm.get_matching_blocks():
    print(block)
# Match(a=0, b=0, size=7)  -> 'Python '
# Match(a=8, b=13, size=1) -> 'P'
# Match(a=11, b=19, size=2) -> 'ng'
# Match(a=18, b=23, size=0) -> EOF

for tag, i1, i2, j1, j2 in sm.get_opcodes():
    print(f"{tag:7} s1[{i1}:{i2}]={s1[i1:i2]!r} -> s2[{j1}:{j2}]={s2[j1:j2]!r}")

Opcodes Output

equal    s1[0:7]=Python  -> s2[0:7]=Python 
replace  s1[7:18]=Programming -> s2[7:19]=Standard Li
delete   s1[18:19]=g -> s2[19:19]=
insert   s1[19:19]= -> s2[19:23]=brar
equal    s1[19:20]= -> s2[23:24]=
equal    s1[20:21]=n -> s2[24:25]=n
equal    s1[21:22]=g -> s2[25:26]=g

Class: Differ

Line-by-line Diff (Human-readable)

import difflib

text1 = '''line 1
line 2
line 3'''.splitlines(keepends=True)

text2 = '''line 1
line 2 modified
line 3
line 4'''.splitlines(keepends=True)

d = difflib.Differ()
diff = list(d.compare(text1, text2))
print(''.join(diff))

ผลลัพธ์

  line 1
  line 2
- line 2
+ line 2 modified
  line 3
+ line 4

Prefix: (Same), - (Delete), + (Add), ? (Change Hint)


Class: HtmlDiff

สร้าง HTML Diff Table (Side-by-side หรือ Inline)

hd = difflib.HtmlDiff(wrapcolumn=60)
html_output = hd.make_file(text1, text2, fromdesc='Original', todesc='Modified')
with open('diff.html', 'w') as f:
    f.write(html_output)

Unified Diff & Context Diff (คล้าย Unix diff)

import difflib, sys

# Unified Diff (Format: diff -u)
for line in difflib.unified_diff(text1, text2, lineterm=''):
    print(line)

# Context Diff (Format: diff -c)
for line in difflib.context_diff(text1, text2, lineterm=''):
    print(line)

Unified Diff Output

--- 
+++ 
@@ -1,3 +1,4 @@
 line 1
 line 2
-line 2
+line 2 modified
 line 3
+line 4

File Comparison Utilities

# Compare 2 Files
with open('file1.txt') as f1, open('file2.txt') as f2:
    diff = difflib.unified_diff(f1.readlines(), f2.readlines(), 
                                 fromfile='file1.txt', tofile='file2.txt')
    sys.stdout.writelines(diff)

# Get Close Matches (Fuzzy Matching)
matches = difflib.get_close_matches('aple', ['apple', 'banana', 'cherry', 'apricot'], n=3, cutoff=0.6)
print(matches)  # ['apple', 'apricot']

การประยุกต์ใช้จริง

  • Version Control Diff Engine
  • Plagiarism Detection
  • Config File Comparison
  • Log Analysis (Before/After)
  • Auto-correction / Fuzzy Search
  • Testing: Assert Multi-line Strings