[英]Extract numbers from specific lines of a text file starting with strings in Python
我正在编写一个代码,我需要从文本文件中读取数据,并从中提取特定的数字。 我已经尝试过 numpy loadtxt 和 genfromtxt,但仍在努力寻找答案。 这是我需要从中提取数据的文件示例:
#
#Text
#
# =============================
# Text
# Text
# Text
# Text
# Text
# =============================
/gps/ene/type Arb
/gps/hist/type arb
/gps/hist/point 9.200000E-04 1.835400E+11
/gps/hist/point 1.200000E-03 1.577700E+11
/gps/hist/point 1.600000E-03 1.348800E+11
/gps/hist/point 2.100000E-03 1.137300E+11
/gps/hist/point 2.700000E-03 9.759600E+10
/gps/hist/point 3.500000E-03 8.348800E+10
/gps/hist/point 4.500000E-03 6.868300E+10
/gps/hist/point 5.900000E-03 5.317300E+10
/gps/hist/point 7.700000E-03 3.917900E+10
/gps/hist/point 1.000000E-02 2.723300E+10
/gps/hist/point 1.300000E-02 1.762600E+10
/gps/hist/point 1.700000E-02 1.058500E+10
/gps/hist/point 3.000000E-02 3.548700E+09
/gps/hist/point 6.100000E-02 1.274400E+09
/gps/hist/point 8.900000E-02 5.074400E+08
/gps/hist/point 1.300000E-01 1.705900E+08
/gps/hist/point 1.800000E-01 7.722800E+07
/gps/hist/point 2.700000E-01 2.671600E+07
/gps/hist/point 4.000000E-01 9.265800E+06
/gps/hist/point 6.100000E-01 2.225000E+06
/gps/hist/point 9.100000E-01 6.600100E+05
/gps/hist/point 1.280000E+00 2.264300E+05
/gps/hist/point 1.990000E+00 4.632400E+04
/gps/hist/point 2.440000E+00 1.928300E+04
/gps/hist/point 3.070000E+00 6.847300E+03
/gps/hist/point 3.970000E+00 1.584400E+03
/gps/hist/point 5.200000E+00 0.000000E+00
#
#Normalisation
#
/control/alias NORM_FACTOR_SPECTRUM " 2.945935E+17 "
/control/alias NORM_FACTOR_ANGULAR " 2.500000E-01 "
我只需要获取以“/gps/hist/point”开头的行之后的数字,并将它们放入二维数组中。 有什么解决办法吗?
提前谢谢了!
myList = []
lines = [line for line in open('myfile.txt', 'r')]
for line in lines:
if line.startswith('/gps/hist/point'):
myList.append([line.split()[1], line.split()[2])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.