开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜