Trong hướng dẫn này, chúng ta tìm các chuỗi trong danh sách "khớp gần đúng" (close match) với một chuỗi cho trước.
Định nghĩa "khớp gần đúng"
Chuỗi A khớp gần đúng chuỗi B nếu A bắt đầu bằng B hoặc B bắt đầu bằng A.
Ví dụ
strings = ["Lion", "Li", "Tiger", "Tig"] element = "Lion" Output: Lion Li
Code sử dụng startswith()
strings = ["Lion", "Li", "Tiger", "Tig"]
element = "Lion"
for s in strings:
if s.startswith(element) or element.startswith(s):
print(s, end=" ")
print()
Kết quả
Lion Li
Mở rộng: Tìm fuzzy match với difflib
Để tìm match gần đúng hơn (sai sót chính tả), dùng difflib.get_close_matches():
import difflib words = ["apple", "aple", "banana", "bandana", "cherry"] target = "appl" matches = difflib.get_close_matches(target, words, n=3, cutoff=0.6) print(matches) # ['apple', 'aple']
Kết luận
startswith() phù hợp cho prefix matching. difflib phù hợp cho fuzzy matching (tìm kiếm mờ).