Tcl在文本文件中查找最小值

时间:2016-07-05 11:27:51

标签: tcl min

我有一个包含数千个值的文本文件和一些像这样的字母数字字符:

\Test1
    +3.00000E-04
    +5.00000E-04
    +4.00000E-04

现在我想扫描这个文件并将值写入变量。

set path "C:/test.txt"
set in  [open $path r]

while {[gets $in line] != -1} { 
set Cache [gets $in line]      
if { $Cache < $Cache }  {
set lowest "$Cache"
}
}

有人有想法吗?我得到一个警告,告诉我目录无法删除?!

BR

1 个答案:

答案 0 :(得分:2)

您可以使用核心数学函数tcl::mathfunc::min。如果存在“垃圾”(即包含不是数字的文本的行),您可以先将这些行过滤掉:

set numbers {}
set f [open test.txt]
while {[gets $f line] >= 0} {
    if {[string is double -strict $line]} {
        lappend numbers [string trim $line]
    }
}
close $f
tcl::mathfunc::min {*}$numbers
# => +3.00000E-04

如果每一行都是有效的双精度浮点数,则可以省去过滤:

set f [open test.txt]
set numbers [split [string trim [read $f]]]
close $f
tcl::mathfunc::min {*}$numbers
# => +3.00000E-04

如果你可以使用Tcllib模块fileutil,如果你的安装上没有它可以从the Tcllib site轻松获取(它已经包含在ActiveTcl安装中),你可以简化代码有些:

package require fileutil 

set numbers {}
::fileutil::foreachLine line test.txt {
    if {[string is double -strict $line]} {
        lappend ::numbers [string trim $line]
    }
}
tcl::mathfunc::min {*}$numbers

package require fileutil 

tcl::mathfunc::min {*}[split [string trim [::fileutil::cat test.txt]]]

文档: >= (operator)closefileutil (package)getsiflappendnamespaceopenpackagereadsetsplitstringwhile{*} (syntax)Mathematical functions for Tcl expressions

相关问题