5-1贝叶斯拼写检查器实现

版权声明:此文章有作者原创,涉及相关版本问题可以联系作者,[email protected] https://blog.csdn.net/weixin_42600072/article/details/88643802

基于贝叶斯公式的实时拼接检查器

import re, collections
# 将语料库中字母转换为小写,并匹配所有字母
def words(text):
    return re.findall('[a-z]+', text.lower())
# 遇到新单词设置默认词频率,并统计词频
def train(features):
    # 遇到新的单词,设置词频默认为1(表示很小的概率)
    model = collections.defaultdict(lambda:1)
    for f in features:
        model[f] += 1
    return model
# 导入语料库返回一个字典,单词为键,值为词频率
NWORDS = train(words(open('./data/big.txt').read()))
# 建立一个字母表
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def edits1(word):
    splits=[]
    # 将单词切成a,b两部分,并传入splits
    # 如:the: ('',the) (t,he) (th,e) (the,'')
    for i in range(len(word)+1):
        splits.append((word[:i],word[i:])) # word[:i]切片第i个元素之前所有元素
                                           # word[i:]切片第i个元素及之后所有元素
                                           # word[a:b]切片[a,b)
    # 单词少写一个字母的可能性
    deletes=[a+b[1:] for a,b in splits if b]
    
    # 单词多写一个字母的可能性
    inserts=[a+c+b for a,b in splits for c in alphabet]
   
    # 单词写错一个字母的可能性
    replaces=[a+c+b[1:] for a,b in splits for c in alphabet if b]
   
    # 单词相邻字母顺序写错的可能性
    transposes=[a+b[1]+b[0]+b[2:] for a,b in splits if len(b)>1]
    
    # 返回一个无序的写错单词的可能性集合(编辑距离为1)
    return set(deletes+transposes+replaces+inserts)
def known_edits2(word):
    # 返回一个无序的写错单词的可能性集合,并包含在语料库中(在1的基础上,编辑距离为2)
    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)
#appl #appla #learw #tess #morw
correct('knon')
'know'

求解:argmaxc P(c|w) -> argmaxc P(w|c) P© / P(w)

  • P©, 文章中出现一个正确拼写词 c 的概率, 也就是说, 在英语文章中, c 出现的概率有多大
  • P(w|c), 在用户想键入 c 的情况下敲成 w 的概率. 因为这个是代表用户会以多大的概率把 c 敲错成 w
  • argmaxc, 用来枚举所有可能的 c 并且选取概率最大的

猜你喜欢

转载自blog.csdn.net/weixin_42600072/article/details/88643802
今日推荐