2015-11-17 21 views
2

如何單獨下面的文本文件,並只保留需要的數據對應:解析文本文件中的TCL和創建鍵值對的字典,其中值,以列表形式

例如文本文件具有格式:

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 

解析上述信息與在字典,其中關鍵是受試者(唯一)和對應於對象的值存儲後是通學生姓名列表

+0

我們能爲所有上述信息創建結構,創造structwhere關鍵的名單roll_number字典? –

回答

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} 
+3

而不是計算行號,您可以簡單地在打開文件後獲取$ fp頭。 –

+0

我們可以爲以上所有信息創建結構並創建structwhere列表的字典是roll_number –

相關問題