Write a program that implements a spell checker and autocorrect.
- User
Write a program that implements a spell checker and autocorrect.
Assistant
Write a program that implements a spell checker and autocorrect.
The user wants a program that implements a spell checker and autocorrect.
1. Scope and Requirements:
TextBlob or simple dictionary-based approaches.textblob or pyspellchecker for real-world usage.2. Approach 1: From Scratch (The "Peter Norvig" approach)
3. Approach 2: Using a Library (pyspellchecker)
pyspellchecker is a pure Python port of Norvig's logic, easy to install and use. TextBlob is another option but relies on heavier dependencies (NLTK) sometimes. Let's stick to pyspellchecker or just show a simple TextBlob example. Actually, textblob is very popular for "autocorrect" specifically.4. Structuring the Response:
textblob because it has a dedicated .correct() method.5. Drafting the Code (Mental or Scratchpad):
Library Version:
from textblob import TextBlob
text = "I havv a speling error."
blob = TextBlob(text)
print(blob.correct())
From Scratch Version:
re and explain that a real app needs a file).pyspellchecker library which bundles the data.6. Refining the "From Scratch" Code:
re (regex), collections (Counter).train(): Count word frequencies.edits1(): Generate all edits at distance 1.known(): Filter edits against the dictionary.correct(): Return the best candidate.7. Review against constraints:
8. Final Plan:
pip install textblob.SpellChecker with load_dictionary, check, and suggest.Self-Correction during drafting Method B: Generating all edit distances is computationally expensive if the dictionary is huge. I'll stick to a basic implementation that demonstrates the logic without over-optimizing. I need a dummy corpus. I will include a long string of text in the code to serve as the training data so the code is copy-paste runnable.
Let's write the response.
alphabet = 'abcdefghijklmnopqrstuvwxyz'edits1 function (deletes, transposes, replaces, inserts).known function to filter candidates.This covers both the "how to do it" and "how it works".
pyspellchecker as a middle ground (pure Python, no heavy deps like TextBlob/NLTK, but implements the logic for you).Let's stick to the plan:
Let's refine the "From Scratch" code to be self-contained. I will create a small text block called corpus so the user can run it immediately without downloading files.
The logic looks solid. I will write the code now. Here are two ways to implement a spell checker and autocorrect system in Python.
If you are building an application for production, you should use a library like TextBlob. It uses pre-trained models to check spelling and suggests corrections based on probability.
Prerequisites:
pip install textblob
The Code:
from textblob import TextBlob
def auto_correct_text(text):
# Create a TextBlob object
blob = TextBlob(text)
# Apply the correct() method to fix spelling
corrected_text = blob.correct()
return str(corrected_text)
def check_and_suggest(text):
blob = TextBlob(text)
words = blob.words
print(f"Original: {text}")
for word in words:
# Check if word is spelled correctly
if not word.spellcheck()[0][1] == 1.0: # If confidence is not 100%
suggestions = word.spellcheck()
print(f" - '{word}' might be misspelled. Suggestions: {suggestions}")
# Example Usage
input_text = "I have a speling errur in this sentnce."
# 1. Simple Autocorrect
print("Corrected:", auto_correct_text(input_text))
# 2. Suggestions only
check_and_suggest(input_text)
If you want to understand how spell checkers work (or cannot use external libraries), you can build one using the Levenshtein Distance algorithm.
This method compares a misspelled word against a dictionary of valid words to find the "edit distance" (how many character changes, insertions, or deletions are needed to match).
Prerequisites:
No external libraries are needed, but you need a list of valid words. For this example, I will include a small set, but in a real app, you would load a large text file (like words.txt).
The Code:
import re
from collections import Counter
class SpellChecker:
def __init__(self, dictionary_text):
# Count frequency of words ( helps decide which correction is most likely )
self.words = Counter(re.findall(r'\w+', dictionary_text.lower()))
def probability(self, word):
"Probability of `word`."
N = sum(self.words.values())
return self.words[word] / N
def known(self, words):
"The subset of `words` that appear in the dictionary."
return set(w for w in words if w in self.words)
def candidates(self, word):
"Generate possible spelling corrections for word."
return (self.known([word]) or
self.known(self.edits1(word)) or
self.known(self.edits2(word)) or
[word])
def correction(self, word):
"Most probable spelling correction for word."
return max(self.candidates(word), key=self.probability)
def edits1(self, word):
"All edits that are one edit away from `word`."
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
inserts = [L + c + R for L, R in splits for c in letters]
return set(deletes + transposes + replaces + inserts)
def edits2(self, word):
"All edits that are two edits away from `word`."
return (e2 for e1 in self.edits1(word) for e2 in self.edits1(e1))
# --- Setup a Dummy Dictionary ---
# In a real scenario, load this from a huge file like 'words.txt'
# Source: Project Gutenberg or standard Unix dictionary
sample_corpus = """
natural language processing is a crucial part of artificial intelligence
the spell checker is able to correct words automatically
python is a programming language
welcome to the world of machine learning and deep learning
this is a simple example of a sentence
"""
# Initialize the checker
checker = SpellChecker(sample_corpus)
# --- Testing ---
misspelled_words = ["langage", "prgramming", "simpple", "cheker"]
print(f"{'Misspelled':<15} | {'Correction':<15}")
print("-" * 33)
for word in misspelled_words:
corrected = checker.correction(word)
print(f"{word:<15} | {corrected:<15}")
known): We throw away any generated nonsense words that don't exist in our dictionary.probability): If there are multiple valid corrections (e.g., "cat" vs "bat"), we pick the one that appears most frequently in our original text corpus.