[英]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.