File io 从txt文件中提取数据

File io 从txt文件中提取数据,file-io,File Io,我在下面附加的txt文件中得到了一些输入。我想提取变量x1到x6,其中值位于冒号后的第一列。(例如,第一个x2-1.55155599552781E+00) 我已经试过了: data = textscan(fileID,'%s %s %f %f %f') 但这并不奏效。最好的方法是什么 729 6 =========================================================================== solution 1 : t : 1.0000

我在下面附加的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 ==

您没有提到您所在的平台或可用的工具,但这里有一种使用
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
...
或者使用
grep
cut

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

愚蠢而简单的Python:

#!/usr/bin/env python

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


在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']
已转换为浮点数

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']