TCl-Tk 如何从文件中捕获浮点数
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
,其中 returns 是一个列表,然后使用 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"
}
这真的不如一开始就正确理解这些行那么好,而且一次处理一行数据非常简单。
我发现在处理包含一些浮点数的文件时遇到了一些麻烦。 这些是我文件中的一些行:
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
,其中 returns 是一个列表,然后使用 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"
}
这真的不如一开始就正确理解这些行那么好,而且一次处理一行数据非常简单。