parsing text file in tcl and creating dictionary of key value pair where values are in list format

一个人想着一个人 提交于 2021-02-10 12:16:16

问题


How to seperate following text file and Keep only require data for corresponding :

for example text file have Format:

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

after parsing above Information and storing in dictionary where key is subject(unique) and values corresponding to subject is list of pass Student name


回答1:


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]

Output :

Science {Joy Adi} Maths {kumar Piya}


来源:https://stackoverflow.com/questions/33761653/parsing-text-file-in-tcl-and-creating-dictionary-of-key-value-pair-where-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!