Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Thư viện FuzzyWuzzy Python: So sánh chuỗi mờ (Fuzzy String Matching)

FuzzyWuzzy là thư viện so sánh độ tương đồng chuỗi dựa trên khoảng cách Levenshtein. Trả về điểm số 0-100 thay vì True/False.

Cài đặt

pip install fuzzywuzzy
pip install python-Levenshtein  # Tăng tốc độ (C implementation)

Windows: easy_install python-Levenshtein nếu pip lỗi.

Module fuzz: So sánh 2 chuỗi

fuzz.ratio() - Độ tương đồng cơ bản

from fuzzywuzzy import fuzz

print(f"Equal: {fuzz.ratio('tutorialspoint', 'tutorialspoint')}")           # 100
print(f"Case diff: {fuzz.ratio('tutorialspoint', 'TutorialsPoint')}")       # 86
print(f"Space diff: {fuzz.ratio('tutorialspoint', 'Tutorials Point')}")     # 86
print(f"Different: {fuzz.ratio('abcd', 'efgh')}")                           # 0

fuzz.WRatio() - Weighted Ratio (thông minh hơn)

Xử lý case, ký tự đặc biệt, chuỗi con tốt hơn.

print(f"Extra chars: {fuzz.WRatio('tutorialspoint', 'tutorialspoint!!!')}")  # 100
print(f"Case diff: {fuzz.WRatio('tutorialspoint', 'TutorialsPoint')}")       # 100
print(f"Different: {fuzz.WRatio('abcd', 'efgh')}")                           # 0

Module process: Tìm kiếm trong danh sách

from fuzzywuzzy import process

choices = ["apple", "banana", "orange", "grape", "pineapple"]
query = "aple"

# Top 2 matches
results = process.extract(query, choices, limit=2)
print(results)
# [('apple', 90), ('pineapple', 72)]

# Best match
best = process.extractOne(query, choices)
print(best)  # ('apple', 90)

Khi nào dùng FuzzyWuzzy?

  • Tìm kiếm sản phẩm, tên người (gõ sai chính tả).
  • Deduplication dữ liệu (trùng lặp gần đúng).
  • NLP: entity matching, record linkage.
  • Autocomplete, gợi ý tìm kiếm.

Hiệu năng

Levenshtein distance O(n*m). Với dữ liệu lớn (>10k), cân nhắc:

  • Cài python-Levenshtein (C speedup 10x).
  • Dùng RapidFuzz (thay thế nhanh hơn, API tương thích).
  • Lọc trước bằng prefix/trigram trước khi fuzzy match.

Kết luận

FuzzyWuzzy dễ dùng, API đơn giản. WRatio thường tốt hơn ratio. Cho production scale lớn, hãy dùng RapidFuzz.