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

时间:2011-04-19 06:00:08

标签: tcl

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

文件内容为

this is my house and it is very good
this is my village and it is the best 

goodbest必须重复10次。

尽可能帮助我

2 个答案:

答案 0 :(得分:1)

你的意思是什么?

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

答案 1 :(得分:1)

你的问题不清楚。

你的意思是包含“好”或“最佳”的行需要重复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

如果你的意思是实际的话需要重复10次:

while {[gets $fin line] != -1} {
    puts $fout [regsub -all {\y(good|best)\y} $line {& & & & & & & & & &}]
}

该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]
}