我正在设计一个文本处理程序,该程序将从一个长篇条目式文本文档中生成关键词列表,并合并意义相似的词条。市面上有许多度量标准,但我现在面临一个新问题,即如何处理不在我所使用词典中的词汇。
我目前使用的是nltk和Python,但我的问题更为抽象。给定一个不在词典中的词,有什么有效的方法可以将其解析为词典中的词?我目前唯一的解决方案是遍历词典中的词,并选择与输入词编辑距离(Levenshtein距离)最短的词。
显然,这是一种非常缓慢且不切实际的方法,我实际上并不需要词典中绝对最匹配的词,只要它是词典中的词并且相当接近就行。对于解决方案来说,效率对我更重要,但也需要基本的准确性。
关于如何将某个未知词一般性地解析为词典中的已知词,有什么想法吗?
回答:
看起来你需要一个拼写纠正器来匹配词典中的词。下面的代码是有效的,直接取自Peter Norvig的博客 http://norvig.com/spell-correct.html,
import re, collectionsdef words(text): return re.findall('[a-z]+', text.lower()) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return modelNWORDS = train(words(file('big.txt').read()))alphabet = 'abcdefghijklmnopqrstuvwxyz'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 e2 in NWORDS)def known(words): return set(w for w in words if w in NWORDS)def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get)
big.txt 是包含已知词汇的词典。