[英]TCl-Tk How to catch floating point numbers from a file
我在处理包含一些浮点数的文件时遇到了一些麻烦。 这些是我文件中的一些行:
174259 1.264944 -.194235 4.1509e-5
174260 1.264287 -.191802 3.9e-2
174261 1.266468 -.190813 3.9899e-2
174262 1.267116 -.193e-3 4.2452e-2
我想做的是找到我想要的数字所在的行(例如“ 174260”)并提取以下三个数字。
这是我的代码:
set Output [open "Output3.txt" w]
set FileInput [open "Input.txt" r]
set filecontent [read $FileInput]
set inputList [split $filecontent "\n"]
set Desire 174260
set FindElem [lsearch -all -inline $inputList $Desire*]
set Coordinate [ regexp -inline -all {\S+} $FindElem ]
set x1 [lindex $Coordinate 1]
set y1 [lindex $Coordinate 2]
set z1 [lindex $Coordinate 3]
puts $Output "$x1 $y1 $z1"
对于字符串“ {\\ S +}”使用正则表达式方法,我将大括号作为最后一个字符:
1.264287 -.191802 3.9e-2}
我不知道如何只提取数字值而不提取整个字符串。
在这种情况下,我非常想选择最简单的选项。
set Output [open "Output3.txt" w]
set FileInput [open "Input.txt" r]
set Desire 174260
while {[gets $FileInput line] >= 0} {
lassign [regexp -inline -all {\S+} $line] key x1 y2 z1
if {$key == $Desire} {
puts $Output "$x1 $y1 $z1"
}
}
close $FileInput
close $Output
失败的问题是,您正在使用lsearch -all -inline
,它返回一个列表,然后使用regexp
将该列表作为字符串处理。 您应该使用以下方法处理该问题:
foreach found $FindElem {
set Coordinate [ regexp -inline -all {\S+} $found ]
set x1 [lindex $Coordinate 1]
set y1 [lindex $Coordinate 2]
set z1 [lindex $Coordinate 3]
puts $Output "$x1 $y1 $z1"
}
这实际上不像只是一开始就正确理解这些行那样好,并且一次只处理一条数据是非常琐碎的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.