Python用startswith提取文件数值报错:min()参数为空序列的解决
问题修复:从文件提取“Maximum Force”行的Value和Threshold数值并解决空序列错误
问题说明
- 需求:从计算输出文件的Maximum Force行,提取
Value和Threshold两列的数值 - 异常:提取“SCF Done:”行的代码可正常运行,但提取“Maximum Force”行时触发
ValueError: min() arg is an empty sequence错误
相关文件片段
Item Value Threshold Converged? Maximum Force 0.009497 0.000450 NO RMS Force 0.002723 0.000300 NO Maximum Displacement 0.247463 0.001800 NO RMS Displacement 0.065734 0.001200 NO SCF Done: E(RPW91-PW91) = -2381.36459172 A.U. after 1 cycles
现有代码
#!/usr/bin/python3.6 import glob import os def CutMAXFValue( Line: str) -> float: return float(Line.split()[2]) def CutSCFValue( Line: str) -> float: return float(Line.split()[4]) def GrepSCF( Filename: str , StartStep = 1): result = list() Step = StartStep with open(Filename, 'r') as f: lines = f.readlines() for s in lines: if s.startswith("SCF Done:"): result.append( (Step, CutSCFValue(s) ) ) Step += 1 return result def GrepMAXF( Filename: str , StartStep = 1): result = list() Step = StartStep with open(Filename, 'r') as f: lines = f.readlines() for s in lines: if s.startswith("Maximum Force"): result.append( (Step, CutMAXFValue(s) ) ) Step += 1 return result def DraftListSteps(f: str): result = list() SubFiles = GetOutFilesBeginsWith( f ) #support function to read from file MaxRerun = GetMaxRerun( SubFiles ) startstep = 1 for rerun in range(MaxRerun+1): RFiles = GetFilesForRerun( SubFiles, rerun ) DoneFile = next( x for x in RFiles if x.endswith("out") or x.endswith("outERR") ) MAXF = GrepMAXF(DoneFile, startstep) MinStep = min(MAXF, key = lambda x: x[1] ) startstep = MinStep[0] result.append(MAXF) return result
报错信息
Traceback (most recent call last): File "forker.py", line 123, in <module> draft = DraftListSteps( f ) File "forker.py", line 91, in DraftListSteps MinStep = min(MAXF, key = lambda x: x[1] ) ValueError: min() arg is an empty sequence
错误原因
- 行匹配失败:文件中“Maximum Force”行首有空格,
s.startswith("Maximum Force")无法匹配到目标行,导致GrepMAXF返回空列表 - 空序列未处理:直接对空列表调用
min()函数,触发空序列错误
修复方案
1. 修复行匹配逻辑
改用去除行首空格后匹配,或者检查行中是否包含目标字符串,提升鲁棒性:
# 替换GrepMAXF中的判断逻辑 stripped_line = s.strip() if stripped_line.startswith("Maximum Force"):
2. 处理空序列情况
在调用min()前先判断列表是否为空,避免报错:
# 在DraftListSteps中添加判断 if not MAXF: print(f"警告:文件 {DoneFile} 中未找到Maximum Force数据") continue # 跳过当前文件或执行其他处理逻辑
3. 修改提取函数,同时获取Value和Threshold
原函数只提取了Value,现在修改为返回两个数值:
def CutMAXFValues(Line: str) -> tuple[float, float]: parts = Line.split() return float(parts[2]), float(parts[3])
4. 更新GrepMAXF函数存储双数值
def GrepMAXF(Filename: str, StartStep=1): result = list() Step = StartStep with open(Filename, 'r') as f: lines = f.readlines() for s in lines: stripped_line = s.strip() if stripped_line.startswith("Maximum Force"): value, threshold = CutMAXFValues(s) result.append((Step, value, threshold)) Step += 1 return result
完整修复后代码
#!/usr/bin/python3.6 import glob import os def CutSCFValue(Line: str) -> float: return float(Line.split()[4]) def CutMAXFValues(Line: str) -> tuple[float, float]: parts = Line.split() return float(parts[2]), float(parts[3]) def GrepSCF(Filename: str, StartStep=1): result = list() Step = StartStep with open(Filename, 'r') as f: lines = f.readlines() for s in lines: if s.startswith("SCF Done:"): result.append((Step, CutSCFValue(s))) Step += 1 return result def GrepMAXF(Filename: str, StartStep=1): result = list() Step = StartStep with open(Filename, 'r') as f: lines = f.readlines() for s in lines: stripped_line = s.strip() if stripped_line.startswith("Maximum Force"): value, threshold = CutMAXFValues(s) result.append((Step, value, threshold)) Step += 1 return result def DraftListSteps(f: str): result = list() SubFiles = GetOutFilesBeginsWith(f) MaxRerun = GetMaxRerun(SubFiles) startstep = 1 for rerun in range(MaxRerun+1): RFiles = GetFilesForRerun(SubFiles, rerun) DoneFile = next(x for x in RFiles if x.endswith("out") or x.endswith("outERR")) MAXF = GrepMAXF(DoneFile, startstep) if not MAXF: print(f"警告:文件 {DoneFile} 中未找到Maximum Force数据") continue MinStep = min(MAXF, key=lambda x: x[1]) startstep = MinStep[0] result.append(MAXF) return result
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

