2013-09-22 121 views
0

我在下面附加的txt文件中获得了一些输入。我想提取变量x1到x6,其中的值在冒号后的第一个列中。 (例如,对于第一X2 -1.55155599552781E + 00)从txt文件中提取数据

我已经试过:

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.99274E-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 == 

回答

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

已经转换为浮点数