繁体   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