繁体   English   中英

从文件中逐行读取 *TCL

[英]Read line by line from a file *TCL

在 TCL 中,我想从文件(a.txt)中逐行读取

输入文件:


a1 1000.1111 2000.2222

a2 2222.0001 3333.2224。 . .


Output 文件 1:

球a1


Output 文件2:

游戏 [棒球 a1] { 1000.1111 (-10.5) 2000.2222 (+20.785) }

比赛(棒球 a2] { 2222.0001 (-10.5) 3333.2224 (+20.785) )

要逐行读取文件,请在这样的循环中使用gets

set f [open "input.file"]
while {[gets $f line] >= 0} {
    # Do something with $line in here
}
close $f

或在split线上使用read和 go 一次性读取文件:

set f popen "input.file"]
set data [read $f]
close $f

foreach line [split $data "\n"] {
    # Do something with $line in here
}

我不完全理解你实际上希望用这些线条做什么,所以我会让你写那部分。 但是,当您无法确定它们是否简单(您的示例片段简单)时,获取一行单词的最佳方法是:

set words [regexp -all -inline {\S+} $line]

一旦你有了单词列表,你就可以进行一系列的列表操作。 例如,要将一行分成第一个单词和其他单词,请使用lassign

set remaining [lassign $words gameName]

format命令可能有助于生成 output。

puts $outputFile [format "game (Baseball %s) {%s}" $gameName $statistics]

但正如我所说, statistics的产生是我真的不知道该怎么做。

一个非常简单的工作示例如下:

set rfp [open "a.txt" r]
set txt [read $rfp]
close $rfp

set text_lines [split $txt "\n"]

set wfp [open "output.txt" w]

foreach line $text_lines {
    if { $line != {} } {
        set val1 [lindex "$line" 0]
        set val2 [lindex "$line" 1]
        set val3 [lindex "$line" 2]
        puts $wfp "game (Base ball $val1) { $val2 (-10.5) $val3 (+20.785) }"
    }
}

close $wfp

这将生成一个名为output.txt的文件,首先从a.txt读取输入,其中包含您需要的确切(某种)模糊内容,无论它是为了...

空行会被跳过,请记住不会进行进一步的行解析检查,因此这意味着始终需要正确的格式。

Output file 1绝对没有意义。

在需要的地方编辑路径。 再见。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM