2016-09-21 115 views
-3

什麼是一種簡單而靈活的方式來解析和製表輸出,如Unix系統下面的輸出?解析和製表結果

輸出具有以下格式的多個條目:

===================================================== 
====== SOLVING WITH MATRIX small_SPD ==== 
=================================================== 

sizes: 5,5,8 

Solving with Sparse LU AND COLAMD ... 
COMPUTE TIME : 8.9287e-05 
SOLVE TIME : 1.0663e-05 
TOTAL TIME : 9.995e-05 
REL. ERROR : 2.30263e-18 


Solving with BiCGSTAB ... 
COMPUTE TIME : 4.113e-06 
SOLVE TIME : 1.853e-05 
TOTAL TIME : 2.2643e-05 
REL. ERROR : 1.34364e-10 

ITERATIONS : 2 

這應該是表列(或類似):

Matrix  Sizes   Solver    Compute Solve   Total  Rel Error 
small_SPD 5,5,8 Sparse LU AND COLAMD 8.9287e-05 1.0663e-05 9.995e-05 2.30263e-18 
small_SPD 5,5,8  BiCGSTAB   4.113e-06 1.853e-05 2.2643e-05 1.34364e-10 
+2

那麼你是如何在這裏建立你的結果的? – KeepCalmAndCarryOn

+0

使用標準'str'方法(如'.split','.strip'和'.startswith')很容易在Python中執行此操作。如果您遇到問題,請發佈您的代碼並解釋您遇到的具體問題,我們將幫助您解決問題。 –

+1

@ PM2Ring是的,但正如下面的答案所示,在perl中有一種更好,更靈活的方法,這正是我所尋找的。我沒有問過怎麼做,但最簡單和最靈活的方法是什麼。 –

回答

1

如果你只是解析輸出,我對付這樣的:

#!/usr/bin/env perl 
use strict; 
use warnings; 

#set paragraph mode - look for empty lines between records. 
local $/ = ''; 

#init the matrix/size vars. 
my $matrix; 
my $sizes; 

#output order  
my @columns = ("COMPUTE TIME", "SOLVE TIME", "TOTAL TIME", "REL. ERROR"); 

#Column headings. 
print join "\t", "matrix", "sizes", "solver", @columns,"\n"; 

#iterate the data. 
#note - <> is a magic file handle that reads STDIN or 'files specified on command line' 
#that's just like how sed/grep/awk do it. 
while (<>) { 
    #find and set the matrix name 
    #note conditional - this only appears in the 'first' record. 
    if (m/MATRIX (\w+)/) { 
     $matrix = $1; 
    } 
    #find and set the sizes. 
    if (m/sizes: ([\d\,]+)/) { 
     $sizes = $1; 
    } 
    #multi-line pattern match to grab keys and values. 
    #this then maps neatly into a hash. 
    my %result_set = m/^(\w+).*: ([\d\.\-e]+)/gm; 

    #add the solver to the 'set': 
    #and use this test to check if this 'record' is of interest. 
    #skipping the "ITERATIONS" line. 
    my ($solver) = m/Solving with (.*) .../ or next; 
    #print it tab separated. 
    print join "\t", $matrix, $sizes, $solver, @result_set{@columns}, "\n"; 
} 

輸出:

matrix sizes solver Compute Solve Total Rel Error 
small_SPD 5,5,8 Sparse LU AND COLAMD 8.9287e-05 1.0663e-05 9.995e-05 2.30263e-18 
small_SPD 5,5,8 BiCGSTAB 4.113e-06 1.853e-05 2.2643e-05 1.34364e-10 

製表符分隔,這可能對某些應用程序很有用 - 但您可能想用printfformat代替。

+0

thx,這正是我所尋找的,因爲它非常靈活並且易於擴展到其他情況 –