You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Tcl读取CSV文件并按规则生成数据汇总表格?

Tcl处理CSV生成汇总表格解决方案

需求说明

需要读取磁盘上的CSV文件,按规则生成汇总表格:

原始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

目标汇总表格格式

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

计算规则

  • A列:索引1的值为A1/A2/A3时,索引2数值的总和(无匹配则为0)
  • B列:索引1的值为B1/B2/B3时,索引2数值的总和(无匹配则为0)

现有代码问题

你当前的代码手动硬编码了A、B列的数值,没有实现从CSV文件中自动计算的逻辑,需要修改代码完成数据的自动累加统计。

修正后的完整代码

# 替换为你的CSV文件实际路径
set loc "data.csv"

# 初始化数组,存储每个月份的A、B总和,默认初始值为0
array set monthStats {}

set file [open $loc r]
while {[gets $file sline] >= 0} {
    # 去除行首尾空白字符(如换行、空格)
    set sline [string trim $sline]
    if {$sline eq ""} {
        continue ;# 跳过空行
    }
    set lsLine [split $sline ","]
    set month [lindex $lsLine 0]
    set category [lindex $lsLine 1]
    set value [lindex $lsLine 2]

    # 初始化当前月份的A、B统计值(未存在则设为0)
    if {![info exists monthStats($month,A)]} {
        set monthStats($month,A) 0
    }
    if {![info exists monthStats($month,B)]} {
        set monthStats($month,B) 0
    }

    # 根据分类累加对应数值
    switch -glob $category {
        A* { incr monthStats($month,A) $value }
        B* { incr monthStats($month,B) $value }
        # 其他分类(如C1、D1)直接忽略
    }
}
close $file

# 获取所有唯一月份并排序
set monthList [lsort -unique [array names monthStats -glob *,A]]
# 提取纯月份名称(去掉",A"后缀)
set monthList [lmap m $monthList {string range $m 0 end-2}]

# 输出格式化表格
set formatStr {%12s%8s%8s}
puts [format $formatStr "Month" "A" "B"]
foreach month $monthList {
    set aVal [expr {[info exists monthStats($month,A)] ? $monthStats($month,A) : 0}]
    set bVal [expr {[info exists monthStats($month,B)] ? $monthStats($month,B) : 0}]
    puts [format $formatStr $month $aVal $bVal]
}

代码说明

  1. 数组存储统计值:用monthStats数组,键格式为月份,类别(如January,A),方便按月份和类别存储累加值。
  2. 文件读取与处理:逐行读取CSV,拆分数据后根据分类(A或B)累加对应数值,其他分类直接跳过。
  3. 月份列表处理:从数组键中提取所有唯一月份并排序。
  4. 表格输出:按指定格式输出表头和每行数据,不存在的统计值默认显示0。

内容的提问来源于stack exchange,提问作者Rahul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 23:25:43