贝叶斯拼写检查器
p(h+|D) = p(h) * p(D|h+) / p(D) 表示一个单词输错的概率 = 单词的词频 * 一个输错单词的可能的正确单词的数量 p(h-|D) = p(h) * p(D|h-) / p(D) 第一步:读取词库,通过正则找出每个单词,并统计单词的词频 import collections, re #找出所有的单词,并且变成小写 def word(text): return re.findall('[a-z]+', text.lower()) #晒出内容的词频 def train(feature): model = collections.defaultdict(lambda :1) for f in feature: model[f] += 1 return model NWORDS = train(word(open('big.txt').read())) 第二步 : 模拟一个错误单词的其他拼写可能性 alphabet = 'abcdefghijklmnopqrstuvwxyz' # 编辑出其他拼写的可能性 def edits1(word): n = len(word) return set([word[0:i]+word[i+1:] for i in range(n)] + # deletion [word[0:i]+word[i+1]+word[i]+word