在tcl中解析文本文件并创建键值对的字典,其中值以列表格式显示 [英] parsing text file in tcl and creating dictionary of key value pair where values are in list format
本文介绍了在tcl中解析文本文件并创建键值对的字典,其中值以列表格式显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何分隔以下文本文件并仅保留对应的数据:
How to seperate following text file and Keep only require data for corresponding :
例如文本文件的格式:
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
推荐答案
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}
这篇关于在tcl中解析文本文件并创建键值对的字典,其中值以列表格式显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文