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

คำแนะนำคำที่คล้ายกันด้วย Enchant ใน Python

เมื่อเราเขียนบางครั้งมักสะกดคำผิด Python มีโมดูล Enchant ช่วยแก้ปัญหานี้ ใช้ตรวจสอบการสะกดคำและแนะนำการแก้ไขสำหรับคำที่สะกดผิด ยังใช้ในแพ็กเกจตรวจสอบการสะกดคำยอดนิยม เช่น ispell, aspell, MySpell รองรับหลายพจนานุกรมและหลายภาษา

การติดตั้ง

pip install pyenchant

ตัวอย่างการใช้งานพื้นฐาน

>> import enchant
>>> d = enchant.Dict("en_US")
>>> d.suggest("prfomnc")
['prominence', 'performance', 'preform', 'Provence', 'preferment', 'proforma']

โค้ดตัวอย่าง: หาคำที่ใกล้เคียงที่สุด

import enchant
import difflib

d = enchant.Dict("en_US")
my_word = "prfomnc"

dict_scores = {}
max_score = 0
suggestions = set(d.suggest(my_word))

for suggestion in suggestions:
    # คำนวณ similarity ratio
    ratio = difflib.SequenceMatcher(None, my_word, suggestion).ratio()
    dict_scores[ratio] = suggestion
    if ratio > max_score:
        max_score = ratio

print(dict_scores[max_score])  # แสดงคำที่ใกล้เคียงที่สุด

ผลลัพธ์

performance

ออบเจ็กต์ Dict - สำคัญที่สุดใน PyEnchant

แทนพจนานุกรม ใช้ตรวจสอบการสะกดและแนะนำคำ

>> import enchant
>>> d = enchant.Dict("en_US")
>>> d.check("Hello")
True
>>> d.check("Helo")
False

การสร้างพจนานุกรมด้วย Language Tag

>> d = enchant.Dict()
>>> d.tag
'en_AU'
>>> print(d.tag)
en_AU

ฟังก์ชันอื่นๆ ในโมดูล enchant

  • dict_exists - ตรวจสอบว่ามี Dict สำหรับภาษานั้นหรือไม่
  • request_dict - สร้างและคืนค่า Dict object ใหม่
  • list_languages - แสดงรายการภาษาที่มี Dict ให้ใช้
>> enchant.dict_exists("fake")
False
>>> enchant.dict_exists("en_US")
True
>>> d = enchant.request_dict("en_US")
>>> d

>>> enchant.list_languages()
['en', 'en_CA', 'en_GB', 'en_US', 'eo', 'fr', 'fr_CH', 'fr_FR']

ประยุกต์ใช้: สร้าง spell checker, autocomplete, ตรวจสอบการสะกดในแอปพลิเคชันข้อความ