python 实现简单的按关键字、后缀进行本地文件搜索

上代码:

def LocalFileMatching(source: Union[str, list, tuple, None] = None,
                      postfix: Union[str, list, tuple, None] = None,
                      keyword: Union[str, list, tuple] = '',
                      exact: Union[bool] = False) -> list | str:
    occasional_dict = defaultdict(list)
    postfix_empty_dict = defaultdict(bool)
    postfix_empty_dict['EmptyState'] = False
    try:
        def item_append(_folder, _item):
            if len(folder) < 4:
                occasional_path = _folder + _item
            else:
                occasional_path = _folder + '/' + _item
            if isabs(occasional_path):
                occasional_dict['MatchingResult'].append(occasional_path)
            else:
                occasional_dict['MatchingResult'].append(realpath(occasional_path).replace('\\', '/'))
        if source and isinstance(source, str):
            matching_source_path = [source]
        elif source and type(source) in [list, tuple]:
            matching_source_path = source
        else:
            matching_source_path = None

        if isinstance(postfix, str) or postfix is None:
            if postfix is None:
                postfix_empty_dict['EmptyState'] = True
            else:
                postfix = [postfix]
        if postfix:
            for item in postfix:
                if item is None:
                    postfix_empty_dict['EmptyState'] = True
                else:
                    occasional_dict['PostFix'].append(sub('\W', '', item))
        keyword = '' if keyword is None else keyword
        if matching_source_path is None:
            for ascii_char in ascii_uppercase:
                sys_disk = fr'{ascii_char}:/'
                if exists(sys_disk):
                    for folder, cdir, obj in walk(sys_disk):
                        matching_for_postfix = comparition(keyword=keyword, compareobj=obj, exact=exact)
                        for matching_item in matching_for_postfix:
                            get_item_postfix = splitext(matching_item)[-1].lower()
                            if occasional_dict['PostFix'] and postfix_empty_dict['EmptyState']:
                                if get_item_postfix.lower()[1:] in occasional_dict['PostFix'] or not get_item_postfix:
                                    item_append(folder, matching_item)
                                else:
                                    continue
                            elif occasional_dict['PostFix'] and not postfix_empty_dict['EmptyState']:
                                if get_item_postfix.lower()[1:] in occasional_dict['PostFix']:
                                    item_append(folder, matching_item)
                                else:
                                    continue
                            else:
                                item_append(folder, matching_item)
        else:
            for sourceitem in matching_source_path:
                if isfile(sourceitem):
                    occasional_dict['CombinationSource'].append(split(sourceitem)[0])
                elif isdir(sourceitem):
                    occasional_dict['CombinationSource'].append(sourceitem)
                else:
                    continue
            for sourc_path in occasional_dict['CombinationSource']:
                for folder, cdir, obj in walk(sourc_path):
                    folder = folder.replace('\\', '/')
                    matching_for_postfix = comparition(keyword=keyword, compareobj=obj, exact=exact)
                    if matching_for_postfix:
                        for matching_item in matching_for_postfix:
                            get_item_postfix = splitext(matching_item)[-1]
                            if occasional_dict['PostFix'] and postfix_empty_dict['EmptyState']:
                                if get_item_postfix.lower()[1:] in occasional_dict['PostFix'] or not get_item_postfix:
                                    item_append(folder, matching_item)
                                else:
                                    continue
                            elif occasional_dict['PostFix'] and not postfix_empty_dict['EmptyState']:
                                if get_item_postfix.lower()[1:] in occasional_dict['PostFix']:
                                    item_append(folder, matching_item)
                                else:
                                    continue
                            else:
                                item_append(folder, matching_item)
        return occasional_dict['MatchingResult']
    except BaseException as searchError:
        return str(searchError)


def comparition(keyword: any,
                compareobj: any,
                exact: bool,
                similarnumber: float = 0.8):
    regular_result = []
    if isinstance(compareobj, str):
        compareobj = [compareobj]
    if keyword:
        for item in compareobj:
            if isabs(item):
                item = split(item)[-1].lower()
            if exact:
                if isinstance(keyword, list):
                    for key in keyword:
                        if key.lower() in item.lower() and item.strip():
                            regular_result.append(item)
                        else:
                            continue
                else:
                    if keyword.lower() in item.lower()  and item.strip():
                        regular_result.append(item)
                    else:
                        continue
            else:
                if isinstance(keyword, str):
                    keyword = [keyword]
                for char in keyword:
                    equalitycount = 0
                    char = char.lower()
                    for ele in char:
                        if ele in item.lower():
                            equalitycount += 1
                    comoare = SequenceMatcher(a=item, b=char).quick_ratio()
                    if equalitycount == len(char) or comoare >= similarnumber:
                        if item in regular_result:
                            continue
                        else:
                            regular_result.append(item)
                    else:
                        continue
        return regular_result
    else:
        return compareobj

直接调用LocalFileMatching就行了, comparition只是辅助,在LocalFileMatching中已经调用了不管它

参数介绍:

source: Union[str, list, tuple, None] 源路径/文件,支持[str, list, tuple, None]类型
postfix: Union[str, list, tuple, None] 后缀,支持[str, list, tuple, None]类型
keyword: Union[str, list, tuple, None] 关键字,支持[str, list, tuple, None]类型
exact: Union[bool] = False 模式: False-模糊匹配或者True-精确匹配

使用:

伍佰粉和不良人粉在此

python 实现简单的按关键字、后缀进行本地文件搜索_第1张图片

result1 = LocalFileMatching(source = ('D:\AppMusic', 'G:\BaiduNetdiskDownload', "G:\迅雷下载\画江湖之不良人第四季09.mp4"),
                            keyword = ['不良人', '伍佰'],
                            postfix = ['mp4', 'mp3', 'ape', 'flac', 'wav'],
                            exact = False)
for item in result1:
    print(item)

结果:

用时0.025179386138916016 秒

全盘查找:

用时 7 秒 

精确查找:

python 实现简单的按关键字、后缀进行本地文件搜索_第2张图片

为了效率全盘时建议还是加上关键字或者后缀筛选下吧

你可能感兴趣的:(python,pyqt)