簡體   English   中英

Tcl文件內容處理

[英]Tcl file content processing

我有一個包含以下數據的 .csv 文件

January,A1,100 
January,A2,200
January,A3,300
January,B1,100
January,B2,300
February,A1,100
February,A2,200
February,B2,200
March,C1,200
March,B1,400
April,D1,100

我需要從磁盤讀取上面的 .csv 文件,處理它並顯示它的摘要如下。 如何將上述原始數據轉換為以下值?

Month       A     B
January    600   400
February   300   200
March        0   400
April        0     0

當索引 1 為 A1/A2/A3 時,A 的公式是索引 2 中的值的總和(如果不可用則為 0)

當索引 1 值為 B1/B2/B3 時,B 的公式是索引 2 中的值的總和(如果不可用則為 0)

我嘗試了什么:

set file [open $loc r]
while {[gets $file sline] >=0} {
  regsub {"(.*?),(.*?)"} $sLine {\1:\2} sLine 
  set lsLine [split $sLine ","]
  set month [lindex $lsLine 0]
  lappend mnList $month
  set monthList [lsort -unique $mnList]
}

我確實用下面的代碼找出了格式化部分。

set Month $monthList 
set A {600 300 0 0}
set B {400 200 400 0}

set formatStr {%15s%15s%15s}
puts [format $formatStr "Month" "A" "B"]
foreach month $Month a $A b $B {
puts [format $formatStr $month $a $b]
}  

我很難從文件中計算 A 和 B 列的值。 我在foreach month $monthList中嘗試了多種方法,但沒有一種方法能幫助我獲得我需要的值:(

PS 對 tcl 和編碼很陌生

set file [open file.csv r]
set data {}
while {[gets $file line] != -1} {
    lassign [split $line ,] month key value
    dict update data $month monthData {
        dict incr monthData [string range $key 0 0] $value
    }
}
# $data contains:
# January {A 600 B 400} February {A 300 B 200} March {C 200 B 400} April {D 100}

proc dictGetDef {dictValue key default} {
    if {![dict exists $dictValue $key]} {
        return $default
    }
    return [dict get $dictValue $key]
}

dict for {month monthData} $data {
    puts [format {%-10s %5d %5d} $month [dictGetDef $monthData A 0] [dictGetDef $monthData B 0]]
}
January      600   400
February     300   200
March          0   400
April          0     0

Tcl 8.7 本身有dict getdef ,但更好。


可以通過幾種方法來限制對一組特定鍵的累積。 使用 switch 使其非常明確:

while {[gets $file line] != -1} {
    lassign [split $line ,] month key value
    switch -- $key {
        A1 - A2 - A3 -
        B1 - B2 - B3 {
            dict update data $month monthData {
                dict incr monthData [string range $key 0 0] $value
            }
        }
    }
}

你給switch模式體對。 如果身體是-那么它會掉落到下一個身體。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM