How to build a spell corrector with Python
In this shot, we will build an NLP engine that will correct the spellings of misspelled words.
We will use the Python package TextBlob to build this application. Install it using the following command:
`pip install textblob`
What is TextBlob?
TextBlob is a Python library used to process text data. It provides a simple and consistent API that can perform common natural language processing tasks. These tasks include POS tagging, noun-phrase extraction, analyzing sentiments, classifying text, translating text, and much more.
Now, let’s move to the coding portion below.
Code
from textblob import TextBlobmisspelled_words = ["Natral", "Langage", "Procesing"]corrected_words = []for word in misspelled_words:corrected_words.append(TextBlob(word).correct())print("Wrong words:", misspelled_words)print("Corrected Words:")for word in corrected_words:print(word, end=" ")
Explanation
- In line 1, we import our required package.
- In line 3, we define a list of words that are misspelled.
- In line 4, we define an empty list that will contain the
TextBlobobjects. (These objects are nothing but words converted toTextBlob.) - In lines 6 and 7, we iterate over all the misspelled words and then store the corresponding
TextBlobobject in that empty list. - In line 9, we print all the misspelled words in our list.
- In lines 12 and 13, we iterate over each
TextBlobobject. We then use thecorrect()method of theTextBlobclass to convert the misspelled word into its correct form. - Finally, we print the correct word.
This is how you can write a Python program that corrects spelling using the TextBlob library. This feature is convenient in Natural language processing tasks.