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

Tìm các từ khớp gần đúng (close matches) từ danh sách trong Python


Cho một từ, tìm các từ trong danh sách có mẫu giống gần đúng (khớp mờ). Sử dụng module difflib và hàm get_close_matches.

Cú pháp

difflib.get_close_matches(word, possibilities, n, cutoff)
word: từ cần tìm khớp.
possibilities: danh sách mẫu so khớp.
n: số lượng kết quả tối đa (>0).
cutoff: ngưỡng điểm tương đồng (0-1), mặc định 0.6.

Ví dụ minh họa

from difflib import get_close_matches
word = 'banana'
patterns = ['ana', 'nana', 'ban', 'ran', 'tan']
print('Từ khớp gần:', get_close_matches(word, patterns))
# ['nana', 'ban', 'ana']