我有这样的文件:
# BJD K2SC-Flux EAPFlux Err Flag Spline
2457217.463564 5848.004 5846.670 6.764 0 0.998291
2457217.483996 6195.018 6193.685 6.781 1 0.998291
2457217.504428 6396.612 6395.278 6.790 0 0.998292
2457217.524861 6220.890 6219.556 6.782 0 0.998292
2457217.545293 5891.856 5890.523 6.766 1 0.998292
2457217.565725 5581.000 5579.667 6.749 1 0.998292
2457217.586158 5230.566 5229.232 6.733 1 0.998292
2457217.606590 4901.128 4899.795 6.718 0 0.998293
2457217.627023 4604.127 4602.793 6.700 0 0.998293
我需要找到并计算Flag = 1的行数(第5列)。以下是我的做法:
foundlines=[]
c=0
import re
with open('examplefile') as f:
for index, line in enumerate(f):
try:
found = re.findall(r' 1 ', line)[0]
foundlines.append(index)
print(line)
c+=1
except:
pass
print(c)
在Shell中,我只需要执行
grep " 1 " examplefile | wc -l
就可以了,这比上面的Python脚本要短得多。虽然Python脚本也能工作,但我想知道是否有一种比上面的脚本更短、更紧凑的方法来完成这个任务? 我更喜欢Shell的简洁性,所以我想在Python中找到类似的东西。
1
,只需使用if ' 1 ' in line
即可。 - Wiktor Stribiżew