Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从文本字符串中查找关键字列表并查找不精确的匹配项_Python_Django - Fatal编程技术网

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距离”。