在所有正确的拼写词中, 我们想要找一个正确的词 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)
import re
# 读取内容
text = open('D:/数据/').read()
# print(text)
# 转小写,只保留a-z字符
text = re.findall('[a-z]+', text.lower())
print(text)dic_words = {}
for t in text:dic_words[t] = (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 = 0for c in candidates:if dic_words[c] >= max_num:max_num = dic_words[c]candidate = creturn candidateprint(correct('learww'))
本文发布于:2024-01-31 08:33:59,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170666124227188.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |