解析tcl中的文本文件并创建键值对的字典,其中值为列表格式

时间:2015-11-17 16:07:36

标签: dictionary tcl text-parsing

如何分隔以下文本文件并保留仅需要相应的数据:

例如文本文件具有格式:

Name Roll_number Subject Experiment_name Marks Result
Joy  23          Science Exp related to magnet 45 pass
Adi  12          Science Exp electronics       48 pass
kumar 18         Maths   prime numbers         49 pass
Piya 19          Maths   number roots          47 pass
Ron 28           Maths   decimal numbers       12 fail

解析上面的信息并存储在字典中,其中键是主题(唯一),并且对应于主题的值是通过学生名称的列表

1 个答案:

答案 0 :(得分:3)

set studentInfo [dict create]; # Creating empty dictionary
set fp [open input.txt r]
set line_no 0
while {[gets $fp line]!=-1} {
    incr line_no
    # Skipping line number 1 alone, as it has the column headers
    # You can alter this logic, if you want to 
    if {$line_no==1} {
        continue
    }
    if {[regexp {(\S+)\s+\S+\s+(\S+).*\s(\S+)} $line match name subject result]} {
        if {$result eq "pass"} {
            # Appending the student's name with key value as 'subject'
            dict lappend studentInfo $subject $name
        }
    }
}
close $fp
puts [dict get $studentInfo]

输出

Science {Joy Adi} Maths {kumar Piya}