拼写纠错、分词
编辑距离的计算:编辑距离可以用来计算两个字符串的相似度,它的应用场景很多,其中之一是拼写纠正(spell correction)。 编辑距离的定义是给定两个字符串str1和str2, 我们要计算通过最少多少代价cost可以把str1转换成str2.
举个例子:
输入: str1 = “geek”, str2 = “gesek”
输出: 1
插入 's’即可以把str1转换成str2
输入: str1 = “cat”, str2 = “cut”
输出: 1
用u去替换a即可以得到str2
输入: str1 = “sunday”, str2 = “saturday”
输出: 3
我们假定有三个不同的操作: 1. 插入新的字符 2. 替换字符 3. 删除一个字符。 每一个操作的代价为1.
动态规划方程:
# 词典库
vocab = set([line.rstrip() for line in open('vocab.txt')])
# print(vocab)
# 生成所有的候选集合
def generate_edit_one(word):
"""
word: 给定的输入(错误的输入)
返回所有(valid)候选集合
"""
# 生成编辑距离为1的单词
# 1.insert 2. delete 3. replace
# appl: replace: bppl, cppl, aapl, abpl...
# insert: bappl, cappl, abppl, acppl....
# delete: ppl, apl, app
# 假设使用26个字符
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i],word[i:]) for i in range(len(word)+1)]
# inserts操作
inserts = [L+c+R for L,R in splits for c in letters]
# delete操作
deletes = [L+R[1:]for L,R in splits if R]
# replace操作
replaces = [L+c+R[1:]for L,R in splits if R for c in letters]
candidates = set(inserts + deletes + replaces)
# 过滤掉不存在词典库里的单词
return [word for word in candidates if word in vocab]
def generate_edit_two(str):
"""
给定一个字符串,生成编辑距离不大于2的字符串
"""
return [e2 for e1 in generate_edit_one(str) for e2 in generate_edit_one(e1) if e2 in vocab]
print('给定一个字符串,生成编辑距离为1的字符串','\n',generate_edit_one('apple'))
print ('给定一个字符串,生成编辑距离不大于2的字符串','\n',generate_edit_two("apple"))
apple的编辑距离为1和不大于2的查询结果
拼写纠错功能包括构建语言模型、用户打错的概率统计,还需要上面的词的修改。
# 词典库
vocab = set([line.rstrip(