当前位置: 动力学知识库 > 问答 > 编程问答 >

tcl - Extracting data from a text file and writing it elsewhere

问题描述:

How can I read a file and put the elements in it to a list and write the contents to other file?

the file contents are

this is my house and it is very good

this is my village and it is the best

good and best has to be repeated 10 times.

help me if possible

网友答案:

Did you mean something like that?

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
网友答案:

Your question is unclear.

Do you mean the lines containing "good" or "best" need to be repeated 10 times?

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

If you mean the actual words need to be repeated 10 times:

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

An example for that regsub command:

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

Update

Based on your comments, you might want:

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]
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: