Python - 拼寫檢查



拼寫檢查是任何文字處理或分析的基本要求。Python包pyspellchecker 提供了這項功能,可以查詢可能拼寫錯誤的單詞,並建議可能的更正。

首先,我們需要在Python環境中使用以下命令安裝所需的包。

 pip install pyspellchecker 

現在我們看看如何使用該包來指出拼寫錯誤的單詞,並對可能的正確單詞提出一些建議。

from spellchecker import SpellChecker

spell = SpellChecker()

# find those words that may be misspelled
misspelled = spell.unknown(['let', 'us', 'wlak','on','the','groun'])

for word in misspelled:
    # Get the one `most likely` answer
    print(spell.correction(word))

    # Get a list of `likely` options
    print(spell.candidates(word))

執行上述程式後,我們將得到以下輸出:

group
{'group', 'ground', 'groan', 'grout', 'grown', 'groin'}
walk
{'flak', 'weak', 'walk'}

區分大小寫

如果我們使用Let代替let,這將成為與字典中最接近匹配的單詞的大小寫敏感比較,結果現在看起來不同了。

from spellchecker import SpellChecker

spell = SpellChecker()

# find those words that may be misspelled
misspelled = spell.unknown(['Let', 'us', 'wlak','on','the','groun'])

for word in misspelled:
    # Get the one `most likely` answer
    print(spell.correction(word))

    # Get a list of `likely` options
    print(spell.candidates(word))

執行上述程式後,我們將得到以下輸出:

group
{'groin', 'ground', 'groan', 'group', 'grown', 'grout'}
walk
{'walk', 'flak', 'weak'}
get
{'aet', 'ret', 'get', 'cet', 'bet', 'vet', 'pet', 'wet', 'let', 'yet', 'det', 'het', 'set', 'et', 'jet', 'tet', 'met', 'fet', 'net'}
廣告
© . All rights reserved.