Some problems have been plaguing us during the use of Python spelling checks. In fact, only continuous learning can make better use of this language. In the past few days, I found many spelling mistakes in the comments I wrote in the previous Code. These mistakes are not outrageous. I should be able to use tools to automatically correct most of them.
It is easy to use the Python spelling check script. It is easier to use the ready-made tools such as aspell and ispell.
Google Daniel Peter Norvig wrote an article on How to Write a Spelling Corrector which is worth seeing. Daniel is Daniel, who has 21 lines of Python Spelling check problems and does not need external tools, you only need to read a dictionary file in advance. The edits1 function of this program is copied from niujia.
- #!/usr/bin/python
- # A simple spell checker
- # written by http://www.vpsee.com
- import os, sys, subprocess, signal
- alphabet = 'abcdefghijklmnopqrstuvwxyz'
- def found(word, args, cwd = None, shell = True):
- child = subprocess.Popen(args,
- shellshell = shell,
- stdin = subprocess.PIPE,
- stdout = subprocess.PIPE,
- cwdcwd = cwd,
- universal_newlines = True)
- child.stdout.readline()
- (stdout, stderr) = child.communicate(word)
- if ": " in stdout:
- # remove \n\n
- stdoutstdout = stdout.rstrip("\n")
- # remove left part until :
- left, candidates = stdout.split(": ", 1)
- candidatescandidates = candidates.split(", ")
- # making an error on the first letter of a word is less
- # probable, so we remove those candidates and append them
- # to the tail of queue, make them less priority
- for item in candidates:
- if item[0] != word[0]:
- candidates.remove(item)
- candidates.append(item)
- return candidates
- else:
- return None
- # copy from http://norvig.com/spell-correct.html
- def edits1(word):
- n = len(word)
- return set([word[0:i]+word[i+1:] for i in range(n)] +
- [word[0:i]+word[i+1]+word[i]+word[i+2:] for i in range(n-1)] +
- [word[0:i]+c+word[i+1:] for i in range(n) for c in alphabet] +
- [word[0:i]+c+word[i:] for i in range(n+1) for c in alphabet])
- def correct(word):
- candidates1 = found(word, 'aspell -a')
- if not candidates1:
- print "no suggestion"
- return
- candidates2 = edits1(word)
- candidates = []
- for word in candidates1:
- if word in candidates2:
- candidates.append(word)
- if not candidates:
- print "suggestion: %s" % candidates1[0]
- else:
- print "suggestion: %s" % max(candidates)
- def signal_handler(signal, frame):
- sys.exit(0)
- if __name__ == '__main__':
- signal.signal(signal.SIGINT, signal_handler)
- while True:
- input = raw_input()
- correct(input)
The above is a solution for Python spelling check.