Tcl 从文本文件中提取数据并将其写入其他位置

Tcl 从文本文件中提取数据并将其写入其他位置,tcl,Tcl,如何读取文件并将其中的元素放入列表,然后将内容写入其他文件 文件内容如下: this is my house and it is very good this is my village and it is the best 这是我的房子,非常好 这是我的村庄,它是最好的 good和best必须重复10次 如果可能的话帮帮我你的意思是这样的吗 set fi [open "filename"] set fo [open "outputfile" w] while {[gets $fi line]!

如何读取文件并将其中的元素放入列表,然后将内容写入其他文件

文件内容如下:

this is my house and it is very good this is my village and it is the best 这是我的房子,非常好 这是我的村庄,它是最好的
good
best
必须重复10次


如果可能的话帮帮我你的意思是这样的吗

set fi [open "filename"]
set fo [open "outputfile" w]
while {[gets $fi line]!=-1} {
  if {$line!=""} {
    for {set i 0} {$i<10} {incr i} {
      puts $fo $line
    }
  }
}
close $fi
close $fo
设置fi[打开“文件名”]
设置fo[打开“输出文件”w]
而{[get$fi line]!=-1}{
如果{$line!=“”}{

对于{seti0}{$i你的问题不清楚

你是说包含“好”或“最好”的行需要重复10次吗

set fin [open infile r]
set fout [open outfile w]
while {[gets $fin line] != -1} {
    switch -glob -- $line {
        *good* -
        *best* {
            for {set i 1} {$i <= 10} {incr i} {
                puts $fout $line
            }
        }
        default {
            # what to do for lines NOT containing "good" or "best"?
        }
    }
}
close $fin
close $fout
该regsub命令的示例如下:

set str "these goods are good; that bestseller is the best"
puts [regsub -all {\y(good|best)\y} $str {& & &}]
# prints: these goods are good good good; that bestseller is the best best best
更新

根据您的评论,您可能需要:

array set values {good 10 best 20}
while {[gets $fin line] != -1} {
    regsub -all {\y(good|best)\y} $line {&-$values(&)} line
    puts $fout [subst -nobackslashes -nocommands $line]
}

当{![eof$fi]}{set line[gets$fi];…}
时,您不应执行
操作。请改为:
当{[gets$fi line]!=-1}{…}
[eof]
只有在您试图读取文件末尾之后,才会返回true,因此在读取最后一行之后,您将进行一次额外的while循环迭代。@Glenn:谢谢您的提示。我将修改我的答案。如果good=10和best=20,如果这两个都包含在某个文件中,并且该文件必须读取一个,并且输出为sho怎么办如果good=10和best=20这两个词都包含在某个文件中,并且该文件必须是只读文件,并且输出应如下所示://我是good-10 am best-20 I如果good=10和best=20这两个词都包含在某个文件中,那么该文件必须是只读文件,并且输出应如下所示://我是good-10 am best-20 I只需将good和bad两个词去掉并分别重复10次和20次////前缀s应该是I am good-10am best-20i,类似地,如果有多个这样的行,那么前缀应该以I am good-10am best-20i am next line extracted开始,依此类推,
array set values {good 10 best 20}
while {[gets $fin line] != -1} {
    regsub -all {\y(good|best)\y} $line {&-$values(&)} line
    puts $fout [subst -nobackslashes -nocommands $line]
}