Python按用户输入的层级深度统计路径前缀出现次数
路径层级前缀出现次数统计实现
需求说明
现有input.txt文件存储固定格式日志,需实现路径前缀统计功能,规则如下:
- 提取每行日志中单引号包裹的文件路径
- 程序运行时接收用户输入的正整数,代表要统计的路径层级深度
- 截取对应深度的路径前缀,统计每个前缀的出现次数
- 统计结果按次数降序排列,按
前缀 : 次数的格式输出
输入深度为2时的输出示例:
U_1A/U_2A : 3 U_1A/U_2C : 2 U_1C/U_2B : 2 U_1A/U_2B : 1 U_1B/U_2A : 1 U_1B/U_2B : 1输入深度为3时的输出示例:
U_1A/U_2A/U_3C : 3 U_1A/U_2C/U_3C : 2 U_1C/U_2B/U_3C : 2 U_1A/U_2B/U_3C : 1 U_1B/U_2A/U_3C : 1 U_1B/U_2B/U_3C : 1
现有基础代码
已完成路径提取的基础逻辑如下:
text = open("input.txt", "r") # Loop through each line of the file for line in text: # Remove the leading spaces and newline character line = line.strip() #print(line) # Split the line into words words = line.split(' ') word = words[3] print (word)
补全后的完整实现代码
from collections import defaultdict # 读取文件存储所有有效路径 all_paths = [] with open("input.txt", "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue # 按单引号分割直接提取路径,兼容性优于固定取空格位的写法 path = line.split("'")[1] all_paths.append(path) # 校验用户输入的层级深度 while True: try: depth = int(input("请输入要统计的路径层级深度:")) if depth < 1: print("层级深度必须为正整数,请重新输入") continue break except ValueError: print("输入无效,请输入正整数") # 统计对应深度前缀的出现次数 prefix_count = defaultdict(int) for path in all_paths: path_parts = path.split("/") if len(path_parts) >= depth: target_prefix = "/".join(path_parts[:depth]) prefix_count[target_prefix] += 1 # 按次数降序、同次数按前缀字典序升序排序 sorted_res = sorted(prefix_count.items(), key=lambda item: (-item[1], item[0])) # 按要求格式输出 for prefix, count in sorted_res: print(f"{prefix} : {count}")
实现说明
- 用
with上下文管理器管理文件读写,自动释放文件资源,指定utf-8编码避免乱码 - 优化路径提取逻辑,不受行内空格数量变化影响,鲁棒性更强
- 增加输入合法性校验,用户输入非正整数时提示重输,避免程序崩溃
- 自动跳过实际层级小于输入深度的路径,避免索引报错
- 排序规则与示例完全匹配:优先按出现次数降序,次数相同的前缀按字典序升序排列
内容的提问来源于stack exchange,提问作者Parine
相关产品推荐
相关产品推荐

