Pythonのスペルチェッカーは、文章中のスペルミスをチェックするソフトウェアの機能です。
スペルチェック機能は、ワープロ、電子メールクライアント、電子辞書、検索エンジンなどのソフトウェアやサービスに組み込まれていることが多い。
Python でスペルチェッカーを作る
さっそく、スペルチェックのツールを作ってみましょう。
1. モジュールのインポート
2種類のモジュールでスペルチェックツールを構築します。
- spellchecker モジュール
- textblobモジュール
まず、インストールとインポートから始めましょう。
Pythonでスペルチェッカーを構築するためには、spellcheckerモジュールをインポートする必要があります。
もし、このモジュールがない場合は、pip パッケージマネージャを使ってインストールすることができます。
C:UsersAdmin>pip install spellchecker
|
同じ方法でtextblobモジュールもインストールすることができます。
C:UsersAdmin>pip install textblob
|
2. textblobモジュールによるスペルチェック
Pythonプログラミング言語のTextBlobは、テキストデータを処理するためのPythonライブラリです。
品詞タグ付け、名詞句抽出、感情分析、分類、翻訳など、一般的な自然言語処理タスクに飛び込むためのシンプルなAPIを提供します。
correct() 関数。
入力されたテキストを修正する最も簡単な方法は、correct() メソッドを使うことです。
from textblob import TextBlob
#Type in the incorrect spellinga = "eies"
print("original text: "+str(a))
b = TextBlob(a)
#Obtain corrected spelling as an outputprint("corrected text: "+str(b.correct()))
|
結果を出力すると、以下の様になります。
original text: eiescorrected text: eyes |
3. スペルチェッカーモジュールを使ったスペルチェック
スペルチェッカーモジュールがどのように文の誤りを訂正するのか見てみましょう。
#import spellchecker libraryfrom spellchecker import SpellChecker
#create a variable spell and instance as spellchecker()spell=SpellChecker()
'''Create a while loop under this loop you need to create a variable called a word and make this variable that takes the real-time inputs from the user.'''while True:
w=input('Enter any word of your choice:')
w=w.lower()
'''if the word that presents in the spellchecker dictionary, Itwill print “you spelled correctly" Else you need to find the best spelling for that word''' if w in spell:
print("'{}' is spelled correctly!".format(w))
else:
correctwords=spell.correction(w)
print("The best suggestion for '{}' is '{}'".format(w,correctwords))
|
Enter any word of your choice:gogleThe best suggestion for 'gogle' is 'google' |
このプログラムでは、スペルチェッカーのインスタンスが複数回呼び出されます。
これは大量の単語を保持しています。
もし、スペルミスのある単語を入力した場合、それがスペルチェッカー辞書にない場合は、それを修正します。
これが、このライブラリについて知っておくべき重要なことです。
まとめ
Pythonを使ったスペルチェッカーの作り方について簡単に説明しましたが、Pythonはコーディングが簡単で、学習も理解もしやすく、コード行数も非常に少ないです。