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

Tcl finding min value in a textfile

我有一个包含数千个值和一些字母数字字符的文本文件,如下所示:

\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

您可以使用核心数学函数 tcl::mathfunc::min。如果有 "junk"(即包含非数字文本的行),您可以先过滤掉这些行:

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), close, fileutil (package), gets, if, lappend, namespace, open, package, read, set, split, string, while, {*} (syntax), Mathematical functions for Tcl expressions