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 TextBlob
misspelled_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 TextBlob objects. (These objects are nothing but words converted to TextBlob.)
  • In lines 6 and 7, we iterate over all the misspelled words and then store the corresponding TextBlob object 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 TextBlob object. We then use the correct() method of the TextBlob class 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.

Free Resources