Introduction
When you write a document or assignment, it is always important to check whether all the written spellings are right or not. There are several ways to perform this task. But do you know Python Programming Language provides some libraries for spell checking and correction of words, sentences, or paragraphs?
In this tutorial, we will discuss How to Check and Correct Spelling in Python using Natural Language Processing (in short NLP). Generally, there is more than one third-party library (pyspellchecker, JamSpell, textblob, etc.) available to spell check but we will work with only textblob library here.
We will build two python programs, one is for checking and correcting a single word, and another one is for sentence or paragraph correction. The second program will work at some point at the basic level, not for advanced or complex checking or correction. Working at an advanced level is also possible but that would be a more re-searchable and lengthy task (Many machine learning algorithms and the mechanism is required). For today's task, we will keep it at an elementary stage.
Visit Also: Sentiment Analysis of Amazon Reviews using Python - NLP
Requirements
As we are working with a third-party python library, you have to install textblob in your system before you import it into your program.
Use pip3 instead of pip for Linux users.
👉Install textblob: pip install textblob
Program to Check and Correct a single word in Python
The code is pretty straightforward. First, we import the Word class from textblob module and pass the given word into the Word() class. Later we call the correct() method and store the correct answer in a variable called 'result'. Lastly, we print that answer.
from textblob import Word
def checkSpelling(word):
givenWord = Word(word)
result = givenWord.correct()
print("Correct Answer: ", result)
word = input("Enter Word: ")
checkSpelling(word)
Output
Enter Word: Tigerr
Correct Answer: Tiger
Program to Check and Correct a Sentence and Paragraph in Python
Here we will import TextBlob() class and pass the text into that later. The rest of the code is exactly as same as the previous program.
from textblob import TextBlob
def checkSpelling(text):
givenText = TextBlob(text)
result = givenText.correct()
print("Correct Answer: \n", result)
text = input("Enter Text: ")
checkSpelling(text)
Output
Enter Text: Tiger is the largast livingg cat.
Correct Answer: Tiger is the largest living cat.
Summary
In this tutorial, we discussed how we can check and correct spelling using python programs. We used here a python library called textblob to perform this task. we wrote two python programs here. One is for checking a single word and the other is for checking sentences or paragraphs.
This small feature can be used in a large project where Natural Language Processing (NLP) plays a major role to solve a real-world problem. For any query related to this topic, leave your comment below.
Thanks for reading!💙
PySeek