目的:查找文本中还有Sum/Avg的行中低三个竖线后第一个浮点数
思路:先使用python读取文本中一行,然后分割字符串,查找含有Sum/Avg关键字的行,取出想要的结果
文本局部:
........
| msop0 | 8 326 | 99.4 0.3 0.3 0.3 0.9 25.0 | -0.383 |
|--------+-------------+-----------------------------------------+-------------|
| mspe0 | 8 394 |100.0 0.0 0.0 0.0 0.0 0.0 |-2147483.648 |
|--------+-------------+-----------------------------------------+-------------|
| muor0 | 8 458 |100.0 0.0 0.0 0.0 0.0 0.0 |-2147483.648 |
|--------+-------------+-----------------------------------------+-------------|
| mvxz0 | 8 435 | 99.8 0.0 0.2 0.2 0.5 25.0 | 0.419 |
|--------+-------------+-----------------------------------------+-------------|
| mwie0 | 8 376 |100.0 0.0 0.0 0.0 0.0 0.0 |-2147483.648 |
|==============================================================================|
| Sum/Avg| 224 11172 | 99.8 0.1 0.1 0.1 0.2 8.5 | -0.089 |
|==============================================================================|
| Mean | 8.0 399.0 | 99.8 0.1 0.1 0.1 0.2 8.5 |-2147483.648 |
| S.D. | 0.0 35.4 | 0.2 0.1 0.2 0.1 0.3 9.0 |-2147483.648 |
| Median | 8.0 394.0 |100.0 0.0 0.0 0.0 0.2 12.5 |-2147483.648 |
`------------------------------------------------------------------------------‘
测试程序如下:
>>> ss='| Sum/Avg| 224 11172 | 99.8 0.1 0.1 0.1 0.2 8.5 | -0.089 |' >>> ss '| Sum/Avg| 224 11172 | 99.8 0.1 0.1 0.1 0.2 8.5 | -0.089 |' >>> ss.split('|') ['', ' Sum/Avg', ' 224 11172 ', ' 99.8 0.1 0.1 0.1 0.2 8.5 ', ' -0.089 ', ''] >>> ss.split('|')[1] == ' Sum/Avg' True >>> ss.split('|')[3] ' 99.8 0.1 0.1 0.1 0.2 8.5 ' >>> ss.split('|')[3][0:5] ' 99.8' >>> float(ss.split('|')[3][0:5]) 99.8
参考程序:
f = open("ctm_39phn.filt.sys") # 返回一个文件对象 line = f.readline() # 调用文件的 readline()方法 while line: #print line, # 后面跟 ',' 将忽略换行符 if line.split('|')[1] == ' Sum/Avg': print float(line.split('|')[3][0:5]) # print(line, end = '') # 在 Python 3中使用 line = f.readline() f.close()