拼写检查器原理
在所有正确的拼写词中, 我们想要找一个正确的词 B, 使得对于 w 的条件概率最大。求解:
P(B|w) -> P(w|B) P(B)/ P(w)
比如:appla是条件w,apple和apply是正确的词B,对于apple和apply来说P(w)都是一样的,所以我们在上式中忽略它, 写成:
P(w|B) P(B)
- P(B), 文章中出现这个正确拼写的词 B 的概率, 也就是说, 在英语文章中, B 出现的概率有多大。
- 假设可以认为单词在文章中出现的概率越大,则正确拼写的概率就越大,可以用单词出现次数来代替这个量。好比说, 英语中出现 the 的概率 P(‘the’) 就相对高, 而出现 P(‘zxzxzxzyy’) 的概率接近0(假设后者也是一个词的话).
- P(w|B), 在用户想键入 B 的情况下敲成 w 的概率。这个是代表用户会以多大的概率把 B 敲错成 w。
import re
# 读取内容
text = open('D:/数据/big.txt').read()
# print(text)
# 转小写,只保留a-z字符
text = re.findall('[a-z]+', text.lower())
print(text)
dic_words = {}
for t in text:
dic_words[t] = dic_words.get(t,0) + 1
# print(dic_words)
编辑距离:
两个词之间的编辑距离定义为使用了几次插入(在词中插入一个单字母), 删除(删除一个单字母), 交换(交换相邻两个字母), 替换(把一个字母换成另一个)的操作从一个词变到另一个词.
# 字母表
alphabet = 'abcdefghijklmnopqrstuvwxyz'
#返回所有与单词 word 编辑距离为 1 的集合
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[i+2:] for i in range(n-1)] + # transposition
[word[0:i]+c+word[i+1:] for i in range(n) for c in alphabet] + # alteration
[word[0:i]+c+word[i:] for i in range(n+1) for c in alphabet]) # insertion
#返回所有与单词 word 编辑距离为 2 的集合
#在这些编辑距离小于2的词中间, 只把那些正确的词作为候选词
def edits2(word):
return set(e2 for e1 in edits1(word) for e2 in edits1(e1))
e1 = edits1('something')
e2 = edits2('something')
print(len(e1) + len(e2))
与 something 编辑距离为1或者2的单词居然达到了 114,818 个
优化:只把那些正确的词作为候选词,优化之后edits2只能返回 3 个单词: ‘smoothing’, ‘something’ 和 ‘soothing’
P(w|B)求解:正常来说把一个元音拼成另一个的概率要大于辅音 (因为人常常把 hello 打成 hallo 这样); 把单词的第一个字母拼错的概率会相对小, 等等。但是为了简单起见, 选择了一个简单的方法: 编辑距离为1的正确单词比编辑距离为2的优先级高, 而编辑距离为0的正确单词优先级比编辑距离为1的高.一般把hello打成hallo的可能性比把hello打成halo的可能性大。
def known(words):
w = set()
for word in words:
if word in dic_words:
w.add(word)
return w
# 先计算编辑距离,再根据编辑距离找到最匹配的单词
def correct(word):
# 获取候选单词
#如果known(set)非空, candidates 就会选取这个集合, 而不继续计算后面的
candidates = known([word]) or known(edits1(word)) or known(edits2(word)) or word
# 字典中不存在相近的词
if word == candidates:
return word
# 返回频率最高的词
max_num = 0
for c in candidates:
if dic_words[c] >= max_num:
max_num = dic_words[c]
candidate = c
return candidate
print(correct('learww'))