Python:re.findall结果无法添加到字典键的问题排查
提取文件时间数据后字典为空的问题解决
问题场景
尝试读取文本文件,用re.findall提取其中的时间数据,并将结果列表添加到字典对应的键中,但最终得到空字典。
文件内容如下:
Download Time: 1.234 sec Commit Time: 4.321 sec Reset Time: 6.96969 sec *** Download Time: 8.313412 sec Commit Time: 4.20420 sec Reset Time: 9.699234 sec *** Download Time: 5.678 sec Commit Time: 2.3151 sec Reset Time: 9.325346 sec ***
原代码:
import re timings = { "download": [], "commit": [], "reset": [] } # List of key phrases to look for in the text file pattern = [r"Download Time: ([\d.]+) sec", r"Commit Time: ([\d.]+) sec", r"Reset Time: ([\d.]+) sec"] # Loop through each key phrase and put timing data into proper list # This is not well optimized lol (nested for loops) for i in range(len(pattern)): with open(file, 'r') as f: # Open file contents and search for pattern content = f.read() matches = re.findall(pattern[i], content) # From collected matching phrases, append timing data into proper lists for key in timings: timings.update({key: matches})
错误原因
- 键与模式的对应逻辑完全错误:遍历正则模式时,又循环字典的所有键,用
update把每个键都覆盖为当前模式的匹配结果。比如第一次循环处理Download的匹配,会把download/commit/reset三个键全设为Download的时间列表;最后一次循环处理Reset的匹配,三个键又全被替换成Reset的结果。如果file变量未正确赋值(比如没指定文件名),会导致读取失败,matches为空,最终所有键都被设为空列表。 - 重复打开文件:每次循环都重新打开并读取文件,既低效又没必要。
update的误用:不需要用update批量赋值,直接给对应键赋值更清晰。
修正后的代码
import re timings = { "download": [], "commit": [], "reset": [] } # 建立键与正则模式的一一对应关系 pattern_map = [ ("download", r"Download Time: ([\d.]+) sec"), ("commit", r"Commit Time: ([\d.]+) sec"), ("reset", r"Reset Time: ([\d.]+) sec") ] # 仅读取一次文件内容,避免重复IO操作 with open("your_file.txt", 'r') as f: # 替换为你的实际文件名 content = f.read() # 遍历对应关系,提取数据并赋值到字典 for key, pattern in pattern_map: matches = re.findall(pattern, content) # 可选:将字符串转换为浮点型数值 # matches = [float(num) for num in matches] timings[key] = matches print(timings)
修正说明
- 用
pattern_map明确键和正则模式的对应关系,避免错误覆盖所有键 - 只读取一次文件内容,提升代码效率
- 直接给字典的对应键赋值,逻辑更清晰
- 注意替换代码中的
your_file.txt为实际的文件名,这是原代码中可能导致读取失败的关键问题之一
内容的提问来源于stack exchange,提问作者hacker_man_2021
相关产品推荐
相关产品推荐

