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

หาคำที่ใกล้เคียงที่สุดจากลิสต์ด้วย difflib ใน Python

หาคำที่ Match ใกล้เคียงด้วย difflib.get_close_matches

โมดูล difflib มีฟังก์ชัน get_close_matches สำหรับหาคำที่คล้ายกันจากลิสต์ตัวเลือก

Syntax


difflib.get_close_matches(word, possibilities, n=3, cutoff=0.6)
# word: คำที่ต้องการค้นหา
# possibilities: ลิสต์คำที่เปรียบเทียบ
# n: จำนวนผลลัพธ์สูงสุด
# cutoff: คะแนนขั้นต่ำ (0-1)

ตัวอย่าง


from difflib import get_close_matches
word = 'banana'
patterns = ['ana', 'nana', 'ban', 'ran', 'tan']
print(get_close_matches(word, patterns))
# ['nana', 'ban', 'ana']