Path: blob/master/languages/python/algorithm_spelling.py
1240 views
import re, collections12def words(text): return re.findall('[a-z]+', text.lower())34def train(features):5model = collections.defaultdict(lambda: 1)6for f in features:7model[f] += 18return model910NWORDS = train(words(file('big.txt').read()))1112alphabet = 'abcdefghijklmnopqrstuvwxyz'1314def edits1(word):15splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]16deletes = [a + b[1:] for a, b in splits if b]17transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]18replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b]19inserts = [a + c + b for a, b in splits for c in alphabet]20return set(deletes + transposes + replaces + inserts)2122def known_edits2(word):23return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)2425def known(words): return set(w for w in words if w in NWORDS)2627def correct(word):28candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]29return max(candidates, key=NWORDS.get)303132