


How to implement a spell checker in 21 lines of Python code
Introduction
When you use Google or Baidu search, when entering search content, Google can always provide a very good spelling check. For example, if you enter speling, Google will return immediately. spelling.
The following is a simple but fully functional spelling checker implemented with 21 lines of python code.
Code
import re, collections def words(text): return re.findall('[a-z]+', text.lower()) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model NWORDS = train(words(file('big.txt').read())) alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): return set(w for w in words if w in NWORDS) def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get)
The correct function is the entry point of the program, and incorrectly spelled words passed in will be returned correctly. Such as:
>>> correct("cpoy") 'copy' >>> correct("engilsh") 'english' >>> correct("sruprise") 'surprise'
In addition to this code, as part of machine learning, there should definitely be a large amount of sample data, and big.txt is prepared as our sample data.
Principle behind
The above code is implemented based on Bayesian. In fact, the spelling check implemented by Google Baidu is also implemented through Bayesian, but it is definitely more complicated than this.
First of all, let’s briefly introduce the principle behind it. If the reader has understood it before, you can skip this paragraph.
Given a word, we try to select the most likely correct spelling suggestion (the suggestion may also be the entered word). Sometimes it is unclear (for example, should lates be corrected to late or latest?), and we use probability to decide which one to use as a suggestion. We find the most likely spelling suggestion c from all possible correct spellings related to the original word w:
argmaxc P(c|w)
Through Bayes’ theorem, the above formula can be transformed into
argmaxc P(w|c) P(c) / P(w)
below Let me introduce the meaning of the above formula:
P(c|w) represents the probability that you originally wanted to input word c when you input word w.
P(w|c) represents the probability that the user wants to enter word c but enters w. This can be considered as given.
P(c) represents the probability that word c appears in the sample data
P(w) represents the occurrence of word w in the sample number The probability of
can be determined that P(w) has the same probability for all possible words c, so the above formula can be converted into
argmaxc P(w|c) P(c)
All our codes are based on this The formula comes from the following analysis of the specific code implementation
Code analysis
Use the words() function to extract words in big.txt
def words(text): return re.findall('[a-z]+', text.lower())
re.findall('[a-z] +' uses the python regular expression module to extract all words that meet the condition of '[a-z]+', that is, words composed of letters (regular expressions will not be introduced in detail here, interested students can see regular expressions. Introduction. text.lower() converts text into lowercase letters, that is, "the" and "The" are both defined as the same word.
Use the train() function to calculate the number of occurrences of each word. Train a suitable model
def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model NWORDS = train(words(file('big.txt').read()))
so that NWORDS[w] represents the number of times word w appears in the sample. What should we do if a word does not appear in our sample? The number of times is set to 1 by default, which is implemented here through the collections module and lambda expression. collections.defaultdict() creates a default dictionary, and lambda: 1 sets each value in this dictionary to 1 by default (lambda expression. You can see the introduction to lambda
Now that we have finished processing P(c) in the formulaargmaxc P(w|c) P(c)
, we will next process P(w|c). The probability of entering word c but incorrectly entering word w is measured by the "edit distance" - the number of edits required to change one word into another. An edit may be a deletion, a swap (two adjacent words letters), one insertion, one modification. The following function returns a set of all possible words w that can be obtained by editing c once:
def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts)
Related papers show that 80-95% of spelling errors are related to the intended spelling. The words have only one edit distance. If you feel that one edit is not enough, let’s do it again
def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)
At the same time, there may also be words with an edit distance of 0 times that are spelled correctly:
def known(words): return set(w for w in words if w in NWORDS)
We assume that the probability of 1 edit distance is much greater than 2 times, and 0 times is much greater than 1 edit distance. Next, use the correct function to first select the word with the smallest edit distance, and its corresponding P(w|c) will be larger, as Candidate words, and then select the word with the largest P(c) as the spelling suggestion
def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get
The above is the detailed content of How to implement a spell checker in 21 lines of Python code. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.
