实现匹配形如 D:/test/*abc.txt 的路径通配符
输入:一个包含通配符的路径字符串,例如 D:/test/*abc.txt
输出:匹配所有符合条件的文件路径,例如 D:/test/123abc.txt 和 D:/test/456abc.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| import fnmatch from pathlib import Path
from rich.console import Console
console = Console()
def wildcard_match(path: Path, pattern: str) -> bool: """ 基于文件名/目录名的通配符匹配(支持*、?等通配符)
参数: path: Path对象,待匹配的文件/目录路径 pattern: 字符串,通配符匹配模式(如test*、abc?等)
返回: bool: 匹配结果,True表示path的名称符合pattern,False反之 """ return fnmatch.fnmatch(path.name, pattern)
def backtrack_match(parts: list[str]) -> list[Path]: """ 基于回溯法递归查找符合层级通配符规则的目录路径
核心逻辑: 1. 将目标路径拆分为多个层级部分(如['D:/', '转移文件', 'test*', 'test*']) 2. 从根路径开始,逐层递归匹配每个层级的通配符规则 3. 匹配成功则进入下一层级,匹配失败则回溯到上一层级继续探索其他可能 4. 收集所有完整匹配的路径并返回
参数: parts: 路径层级列表,每个元素为对应层级的路径/通配符规则 示例:['D:/', '转移文件', 'test*', 'test*'] 表示查找 D:/转移文件/以test开头的目录/以test开头的目录
返回: list[Path]: 所有符合层级通配符规则的完整路径列表(Path对象) """ all_paths: list[Path] = [] current_path_state: list[str] = [parts[0]] def backtrack(index: int): """ 递归回溯的核心内部函数
参数: index: 当前正在匹配的路径层级索引(对应parts列表的下标) """ now_looking_at = Path('/'.join(current_path_state)) if index == len(parts): all_paths.append(now_looking_at) console.print(f"[bold green] Answer: {now_looking_at.as_posix()}") return console.print(f"Checking path: {now_looking_at.as_posix()}") for child in now_looking_at.iterdir(): if child.is_dir() and wildcard_match(child, parts[index]): console.print(f' Valid path found: {child.as_posix()}') current_path_state.append(child.name) backtrack(index + 1) current_path_state.pop() console.print(f" Backtracking to: {now_looking_at.as_posix()}")
backtrack(1) return all_paths
def separate_path(p: str) -> list[str]: """ 将路径字符串拆分为层级列表 """ p = p.replace('\\', '/') lst = list(p.split('/')) if lst and ':' in lst[0]: lst[0] += '/' return lst
|
- 核心功能:
backtrack_match 通过回溯递归逐层匹配路径层级的通配符规则,wildcard_match 是底层的通配符匹配工具函数;
- 关键逻辑:递归终止条件是匹配完所有路径层级,回溯操作通过
current_path_state.pop() 实现,确保探索所有可能的路径分支;
- 输出特性:使用
rich 库美化控制台输出。