我篡改了Norvig的拼写修正器来做到这一点。我不得不作弊,并在Norvig的数据文件中加入'checker'这个词,因为它永远不会出现。没有这种欺骗,这个问题真的很难。
expertsexchange expert exchange
spel checker spell checker
spellchecker spell checker
spelchecker she checker # can't win them all
baseball base all # baseball isn't in the dictionary either :(
hewent he went
基本上你需要使更改代码:
- 您添加空间字母自动探索断字。
- 您首先检查构成短语的所有单词是否在字典中以考虑该短语有效,而不是直接字典成员资格(该字典不包含短语)。
- 你需要一种方式来对普通单词进行评分。
后者是最棘手的,我用词组组成的新空房禁地独立性假设,即两个相邻字的概率是他们个人的概率(这里用日志的概率空间和完成)的产品,用小罚款。我相信在实践中,你会想保留一些bigram统计数据来做好分裂。
import re, collections, math
def words(text): return re.findall('[a-z]+', text.lower())
def train(features):
counts = collections.defaultdict(lambda: 1.0)
for f in features:
counts[f] += 1.0
tot = float(sum(counts.values()))
model = collections.defaultdict(lambda: math.log(.1/tot))
for f in counts:
model[f] = math.log(counts[f]/tot)
return model
NWORDS = train(words(file('big.txt').read()))
alphabet = 'abcdefghijklmnopqrstuvwxyz '
def valid(w):
return all(s in NWORDS for s in w.split())
def score(w):
return sum(NWORDS[s] for s in w.split()) - w.count(' ')
def edits1(word):
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [a + b[1:] for a, b in splits if b]
transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b]
inserts = [a + c + b for a, b in splits for c in alphabet]
return set(deletes + transposes + replaces + inserts)
def known_edits2(word):
return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if valid(e2))
def known(words): return set(w for w in words if valid(w))
def correct(word):
candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]
return max(candidates, key=score)
def t(w):
print w, correct(w)
t('expertsexchange')
t('spel checker')
t('spellchecker')
t('spelchecker')
t('baseball')
t('hewent')