在文本中修正拼写错误的最佳算法

时间:2017-07-11 06:06:36

标签: python string algorithm nlp pattern-matching

我有一个单词库列表和一个有拼写错误(拼写错误)的文本,我想根据库列表更正单词拼写错误是正确的

例如

在单词列表中:

listOfWord = [...,"halo","saya","sedangkan","semangat","cemooh"..];

这是我的字符串:

string = "haaallllllooo ssya sdngkan ceemoooh , smngat semoga menyenangkan"

我想改变拼写错误,如:

string = "halo saya sedangkan cemooh, semangat semoga menyenangkan"

检查列表中每个单词的最佳算法是什么,因为我在列表中有数百万个单词并且有很多可能性

6 个答案:

答案 0 :(得分:6)

这取决于您的数据的存储方式,但您可能希望使用模式匹配算法,如Aho–Corasick。当然,这假设您的输入数据结构是Trie。一个Trie非常节省空间的存储容器,用于您可能感兴趣的单词(同样,取决于您的环境。)

答案 1 :(得分:2)

您可以使用difflib获得近距离匹配,但效率不高

words = ["halo","saya","sedangkan","semangat","cemooh"];
def get_exact_words(input_str):
    exact_words = difflib.get_close_matches(input_str,words,n=1,cutoff=0.7)
    if len(exact_words)>0:
        return exact_words[0]
    else:
        return input_str

string = "haaallllllooo ssya sdngkan ceemoooh , smngat semoga menyenangkan"
string = string.split(' ')
exact = [get_exact_words(word) for word in string]

exact = ' '.join(exact)
print(exact)

输出: 使用difflib

haaallllloooo saya sedangkan cemooh,semangat semangat menyenangkan

答案 2 :(得分:1)

我假设您正在为某种语言编写拼写检查程序。

您可能希望将句子标记为单词。

然后将haaallllllooo等字词缩短为haalloo。假设你所使用的语言并没有经常包含许多重复字母的单词。因为你有字典,所以很容易检查。

然后你可以使用这个algorithm/implementation by Peter Norvig。您所要做的就是用词典替换他的正确单词词典。

答案 3 :(得分:1)

您可以使用散列技术来检查正确的模式,这可以在Rabin Karp Algorithm.

的行中找到

您知道列表中原始字符串的哈希值是多少。对于拼写纠正,您可以尝试将这些单词组合起来,然后将它们与字典中存在的原始字符串进行匹配。无论如何,这只需要遍历spellerror列表中的所有字符一次。但它会很有效率。

答案 4 :(得分:0)

您可以使用pyenchant检查拼写单词列表。

>>> import enchant
>>> d = enchant.request_pwl_dict("mywords.txt")
>>> d.check('helo')
False
>>> d.suggest("Helo")
['He lo', 'He-lo', 'Hello', 'Helot', 'Help', 'Halo', 'Hell', 'Held', 'Helm', 'Hero', "He'll"]

您需要拆分单词并逐个检查,如果错误,请选择要替换的第一个建议。 这里的教程中有更多高级功能。 http://pyenchant.readthedocs.io/en/latest/tutorial.html

答案 5 :(得分:0)

我认为您应该使用字符串距离算法来查找最近的算法。您可以应用these算法来查找最近的单词。那些大多是O(n)算法,所以最后你的句子替换最多会花费你O(n)。