从txt文件中提取数据

时间:2013-09-22 19:11:03

标签: file-io

我在下面附带的txt文件中输入了一些内容。我想将变量x1提取到x6,其中值位于冒号后的第一个列中。 (例如,对于第一个x2 -1.55155599552781E + 00)

我已经尝试过了:

data = textscan(fileID,'%s %s %f %f %f')

但那没用。最好的方法是什么?

729 6
===========================================================================
solution 1 :
t :  1.00000000000000E+00   0.00000000000000E+00
m : 1
the solution for t :
 x2 : -1.55155599552781E+00  -2.39714921318749E-46
 x4 : -2.01518902001522E+00   1.29714616910194E-46
 x1 :  1.33015840530650E+00   2.03921256321194E-46
 x6 : -2.10342596985387E+00   1.19910915953576E-46
 x3 :  1.27944237849516E+00   1.99067515607667E-46
 x5 :  2.44955616711054E+00  -1.48359823527798E-46
== err :  2.178E-13 = rco :  2.565E-05 = res :  1.819E-11 ==
solution 2 :
t :  1.00000000000000E+00   0.00000000000000E+00
m : 1
the solution for t :
 x2 :  1.55762648294693E+00   1.44303635803762E-45
 x4 :  2.10025771786320E+00  -6.97912321099274E-46
 x1 : -1.28451613237821E+00  -1.19859598871142E-45
 x6 :  2.01187184051108E+00  -7.54361111776421E-46
 x3 : -1.33529118239379E+00  -1.22818883958157E-45
 x5 : -2.44570040628148E+00   8.62982269594568E-46
== err :  2.357E-13 = rco :  2.477E-05 = res :  1.637E-11 ==

2 个答案:

答案 0 :(得分:1)

您没有提到您所使用的平台或可用的工具,但这是使用awk的一种方式:

$ awk '/^ x[1-6]/{print $3}' your_input
-1.55155599552781E+00
-2.01518902001522E+00
1.33015840530650E+00
-2.10342596985387E+00
1.27944237849516E+00
2.44955616711054E+00
1.55762648294693E+00
2.10025771786320E+00
-1.28451613237821E+00
2.01187184051108E+00
-1.33529118239379E+00
-2.44570040628148E+00

或者,像这样:

$ awk '/^ x[1-6]/{print $1, $3}' f1
x2 -1.55155599552781E+00
...

或使用grepcut

$ grep '^ x[1-6]' your_input | cut -d' ' -f-4,5
 x2 : -1.55155599552781E+00
 ...

的Perl:

perl -lane 'print $F[2] if /^ x[1-6]/' your_input

愚蠢而简单的Python:

#!/usr/bin/env python

with open("f1") as fd:
    for line in fd:
        if line.startswith(' x'):
            print line.strip().split()[2]

sed的:

$ sed -n 's/^ x[1-6] : *\([^ ]*\).*$/\1/p' your_input

答案 1 :(得分:0)

在Python中应该这样做

import re

vars = {}
for x in open("data.txt"):
    m = re.match("^\\s+(x\\d+)\s+:\\s+([^ ]*).*", x)
    if m:
        vars[m.group(1)] = float(m.group(2))
    if re.match("^== err.*", x):
        # Got a full solution
        print vars
        vars = {}

当找到完整的解决方案时,变量可用作

vars['x1']
vars['x2']

已转换为浮点数

相关问题