如何遍历release notes统计每个日期对应的Fix修复记录数量
解决方案
你原有的两次读取文件、匹配行号的方案容易出现边界错误,且IO开销更高,下面的方案仅需单次遍历文件即可完成统计,同时适配你给出的日期行格式:
from collections import defaultdict # 替换为实际的发布说明文件路径 file_name = "release_notes.txt" # 存储日期对应修复次数的字典,默认初始值为0 fix_counter = defaultdict(int) # 记录遍历过程中最近一次的有效日期 latest_date = None with open(file_name, 'r', encoding='utf-8') as f: for line in f: stripped_line = line.strip() # 匹配日期行,处理多冒号、多空格的格式 if stripped_line.startswith("Date"): date_part = stripped_line.split(":")[-1].strip() # 验证日期为YYYY-MM-DD格式再更新 if len(date_part) == 10 and date_part.count("-") == 2: latest_date = date_part # 匹配修复记录行,存在有效日期时累加计数 elif "Fix" in stripped_line and latest_date: fix_counter[latest_date] += 1 # 按要求格式输出结果 for date, count in fix_counter.items(): print(f"Date: {date}") print(f"Fixes: {count}")
如果需要按日期排序输出,可将最后输出部分替换为以下代码:
# 按日期从新到旧降序输出 for date in sorted(fix_counter.keys(), reverse=True): print(f"Date: {date}") print(f"Fixes: {fix_counter[date]}")
内容的提问来源于stack exchange,提问作者yishud
相关产品推荐
相关产品推荐

