Python 代码实现模糊查询


一、概述

最近在做一个django项目,里面有一个字典数据非常大,虽然已经做了分页处理。但是用户想要找到指定的数据,还得一页页翻,非常繁琐。

字典的结构如下:

file_list = [
    {
        "type": "dir",
        "size": "123",
        "name": "access.log",
    },
    {
        "type": "dir",
        "size": "123",
        "name": "access.log.gz",
    },
    {
        "type": "dir",
        "size": "123",
        "name": "error.log",
    },
    {
        "type": "dir",
        "size": "123",
        "name": "access-auth.log",
    },
]

 

当我输入关键字access时,需要出现3个结果。

['access-auth.log', 'access.log', 'access.log.gz']

 

二、代码实现

完整代码如下:

test.py

import re

file_list = [
    {
        "type": "dir",
        "size": "123",
        "name": "access.log",
    },
    {
        "type": "dir",
        "size": "123",
        "name": "access.log.gz",
    },
    {
        "type": "dir",
        "size": "123",
        "name": "error.log",
    },
    {
        "type": "dir",
        "size": "123",
        "name": "access-auth.log",
    },
]


def fuzzy_finder(key, data):
    """
    模糊查找器
    :param key: 关键字
    :param data: 数据
    :return: list
    """
    # 结果列表
    suggestions = []
    # 非贪婪匹配,转换 'djm' 为 'd.*?j.*?m'
    # pattern = '.*?'.join(key)
    pattern = '.*%s.*'%(key)
    # print("pattern",pattern)
    # 编译正则表达式
    regex = re.compile(pattern)
    for item in data:
        # print("item",item['name'])
        # 检查当前项是否与regex匹配。
        match = regex.search(item['name'])
        if match:
            # 如果匹配,就添加到列表中
            suggestions.append(item)

    return suggestions

# 搜索关键字
keys = "access"
result = fuzzy_finder(keys,file_list)
print(result)
View Code

 

执行输出:

[{'type': 'dir', 'size': '123', 'name': 'access.log'}, {'type': 'dir', 'size': '123', 'name': 'access.log.gz'}, {'type': 'dir', 'size': '123', 'name': 'access-auth.log'}]

 

 

本文参考链接:

https://www.cnblogs.com/weiman3389/p/6047017.html


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM