Python 从文本字符串中查找关键字列表并查找不精确的匹配项
我有一个在文本字符串中查找的关键字列表。精确匹配很好,但有人知道库可以帮助进行近似匹配吗?例如,如果我提供的单词列表是Python 从文本字符串中查找关键字列表并查找不精确的匹配项,python,django,Python,Django,我有一个在文本字符串中查找的关键字列表。精确匹配很好,但有人知道库可以帮助进行近似匹配吗?例如,如果我提供的单词列表是 [“你好”,“再见”] 我想看看文本字符串是否有hlelo到了某种程度的“接近度” 有什么建议吗?以下是我的建议。首先,定义一个字符串以搜索并删除无关字符: >>> tosearch = "This is a text string where I typed hlelo but I meant to type hello." >>> imp
[“你好”,“再见”]
我想看看文本字符串是否有hlelo
到了某种程度的“接近度”
有什么建议吗?以下是我的建议。首先,定义一个字符串以搜索并删除无关字符:
>>> 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(" "))
接下来,您可以使用该库查找与给定单词的接近匹配项:
>>> import difflib
>>> difflib.get_close_matches('hello', words)
['hello', 'hlelo']
尝试在搜索中使用术语“Levenshtein距离”。