如何解决更改txt文件中的数字
我有下一个表达式:txt 文件中的 jj_ftfll h\\h\ -0.8898:0.006656 0.998:0.99999 h&j\hhh
,
我需要将 0.005 添加到 0.006656 数字。我想用Tcl,我想不出什么好主意。
解决方法
有几个方面很棘手。
-
文件需要就地编辑,尽管添加可能改变行的长度。 (这样的添加可能会延长或缩短线路。)
-
需要有一种方法来可靠地识别那是要修改的行,而不是文件中的其他行。 (这实际上是现实中这些问题中最难的;它是非常特定于应用程序的。)
-
需要从行中提取数字、修改并写回。
-
您正在处理的值可能(实际上)没有以 IEEE 二进制浮点数精确表示,而 Tcl 将使用它来进行计算。
考虑到所有这些,我们正在讨论以下类型的解决方案:
-
我们将读取整个文件,将其拆分为一个字符串列表,每行一个字符串(以下称为行),更新感兴趣的行,然后将整个文件写回。
-
我们将使用
regexp
来确定一行是否值得关注。到目前为止,这是此类任务最常用的命令。 -
这个在 Tcl 8.6 及之前的版本中很混乱。它在 Tcl 8.7 中有更好的解决方案。
-
对此您真的无能为力。如果你知道数字的范围,你可以使用
format
来帮助......但它很混乱。但也许你会走运。
set filename "foobar.txt"
# Get the lines of the file; this is GREAT if the file isn't too large
set f [open $filename]
set lines [split [read $f] "\n"]
close $f
# Now THAT'S what I call a horrible regular expression!
set RE {^(jj_ftfll\s+h\\\\h\\\s+-?[\d.]+:)(-?[\d.]+)(\s+-?[\d.]+:-?[\d.]+\s+h&j\hhh)$}
set newLines {}
foreach line $lines {
if {[regexp $RE $line -> prefix number suffix]} {
set line $prefix[expr {$number + 0.005}]$suffix
}
lappend newLines $line
}
# Write back over the file; the -nonewline prevents the number of lines from growing
set f [open $filename w]
puts -nonewline $f [join $newLines "\n"]
close $f
regexp
的诀窍是我匹配三个部分:行的位 before 要替换的部分(保存在变量 prefix
中),要替换自身的数字 (number
),以及要替换的部分之后的位 (suffix
); regexp
命令返回匹配的次数(如果找到 RE,则为 1,否则为 0)。这是一个可怕的 RE,主要是因为它有 -?[\d.]+
来匹配那些浮点数,而且我已将空格更改为 \s+
(即“至少一个空格字符”)。
8.7 的版本是这样的:
set filename "foobar.txt"
# Get the lines of the file; this is GREAT if the file isn't too large
set f [open $filename]
set lines [split [read $f] "\n"]
close $f
# Now THAT'S what I call a horrible regular expression!
set RE {^(jj_ftfll\s+h\\\\h\\\s+-?[\d.]+:)(-?[\d.]+)(\s+-?[\d.]+:-?[\d.]+\s+h&j\hhh)$}
proc addDeltaInLine {delta prefix number suffix} {
set number [expr {$number + $delta}]
return [string cat $prefix $number $suffix]
}
set newLines [lmap line $lines {
regsub -command $RE $line {addDeltaInLine 0.005}
}]
# Write back over the file; the -nonewline prevents the number of lines from growing
set f [open $filename w]
puts -nonewline $f [join $newLines "\n"]
close $f
lmap
和 regsub -command
的组合使事情变得更干净了。不过,RE 仍然很可怕……
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。