Peter Norvig 的algorithm 只需稍作改动即可实现。诀窍是在字母表中添加一个空格字符,并将所有由空格字符分隔的二元组视为唯一单词。
由于 big.txt 不包含 deep learning bigram,我们将不得不在字典中添加更多文本。我将使用wikipedia library (pip install wikipedia) 来获取更多文本。
import re
import wikipedia as wiki
import nltk
from nltk.tokenize import word_tokenize
unigrams = re.findall(r"\w+", open("big.txt").read().lower())
for deeplerning in wiki.search("Deep Learning"):
try:
page = wiki.page(deeplerning).content.lower()
page = page.encode("ascii", errors="ignore")
unigrams = unigrams + word_tokenize(page)
except:
break
我将创建一个包含所有 unigrams 和 bigrams 的新字典:
fo = open("new_dict.txt", "w")
for u in unigrams:
fo.write(u + "\n")
bigrams = list(nltk.bigrams(unigrams))
for b in bigrams:
fo.write(" ".join(b)+ "\n")
fo.close()
现在只需在edits1 函数中的letters 变量中添加一个space 字符,将big.txt 更改为new_dict.txt 并更改此函数:
def words(text): return re.findall(r'\w+', text.lower())
到这里:
def words(text): return text.split("\n")
现在correction("deeplerning") 返回'deep learning'!
如果您需要特定域的拼写校正器,此技巧将非常有效。如果这个域很大,您可以尝试只将最常见的一元/二元添加到您的字典中。
这个question 也可能有帮助。