2015-04-30 62 views
1

我有一個.txt文件作爲包含一些感興趣值的程序的輸出。問題是,在某些情況下,這些值有一個奇怪的格式,我無法對它們應用數學運算。浮點數的數學運算

比如:我的文件中包含這些數字:

-2.55622-3 
-0.31-2 
-3.225-2 
... 

這些數字在正常的數學格式應該是:

-2.55622e-03 
-0.31e-02 
-3.225e-02 

當然,如果我嘗試總結這些值,這是錯誤:

can't use non-numeric string as operand of "+" 

我該如何操作我的原始值?我真的沒有想法。 請記住,我無法更改我的.txt文件的值格式

回答

4

另一種方法:

% exec cat file 
-2.55622-3 
-0.31-2 
-3.225-2 
42 
foo 
% set fh [open "file" r] 
% while {[gets $fh line] != -1} { 
    puts -nonewline "\"$line\"\t=> " 
    if {! [regsub {[-+]\d+$} [string trim $line] {e&} num]} {set num $line} 
    puts -nonewline "$num\t=> " 
    puts [expr {$num + 0}] 
} 
"-2.55622-3 " => -2.55622e-3 => -0.00255622 
"-0.31-2"  => -0.31e-2  => -0.0031 
"-3.225-2"  => -3.225e-2 => -0.03225 
"42" => 42 => 42 
can't use non-numeric string as operand of "+" 
"foo" => foo => % 
0

嘗試使用(\d+.\d+)模式的regsub數字。

set fp [open "somefile.txt" r] 
set file_data [read $fp] 
close $fp 
set data [split $file_data "\n"] 
foreach line $data { 
set e "e" 
set number [ regexp -all -inline {(\d+.\d+)} $line ] 
regsub -all {(\d+.\d+)} $number "$number$e" number 

}

例如讀取文件,並通過線分開。

set e "e" 

查找號碼是:

set number [ regexp -all -inline {(\d+.\d+)} $line ] 

然後更換

regsub -all {(\d+.\d+)} $number "$number$e" number 
+1

我不知道這是最好的解決方案,因爲OP沒」不要提這些是文件中唯一的數字。我的意思是,你可以有一個像'2.3'這樣的行,並且你的代碼會將它轉換爲'2.3e',即使'2.3-4'被正確地轉換爲'2.3e-4',這也是不正確的。 – Jerry