从文本字符串中找到关键词列表并查找不精确匹配
我有一串关键词,想在一段文字中找到它们。完全匹配的效果很好,但有没有人知道有什么库可以帮助我找到相似的匹配?比如说,如果我提供的关键词是 ["hello", "bye"]
,我希望它能检测到文字中有 hlelo
这样的相似词,达到一定的“接近度”。有没有什么推荐的?
1 个回答
3
我会这样做。首先,定义一个要搜索的字符串,并去掉多余的字符:
>>> tosearch = "This is a text string where I typed hlelo but I meant to type hello."
>>> import string
>>> exclude = set(string.punctuation)
>>> tosearch = ''.join(ch for ch in tosearch if ch not in exclude)
>>> tosearch
'This is a text string where I typed hlelo but I meant to type hello'
>>> words = set(tosearch.split(" "))
接下来,你可以使用 difflib 这个库来找到与给定单词相近的匹配项:
>>> import difflib
>>> difflib.get_close_matches('hello', words)
['hello', 'hlelo']