FuzzySearch.py 文件源码

python
阅读 22 收藏 0 点赞 0 评论 0

项目:CorpBot.py 作者: corpnewt 项目源码 文件源码
def search(searchTerm, list, keyName : str = None, numMatches : int = 3):
    """Searches the provided list for the searchTerm - using a keyName if provided for dicts."""
    if len(list) < 1:
        return None
    # Iterate through the list and create a list of items
    searchList = []
    for item in list:
        if keyName:
            testName = item[keyName]
        else:
            testName = item
        matchRatio = difflib.SequenceMatcher(None, searchTerm.lower(), testName.lower()).ratio()
        # matchRatio = Levenshtein.ratio(searchTerm.lower(), testName.lower())
        searchList.append({ 'Item' : item, 'Ratio' : matchRatio })
    # sort the servers by population
    searchList = sorted(searchList, key=lambda x:x['Ratio'], reverse=True)
    if numMatches > len(searchList):
        # Less than three - let's just give what we've got
        numMatches = len(searchList)
    return searchList[:numMatches]
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号