2017-03-09 44 views
0

我是一個絕對的初學者,不能完全包圍Tcl。我需要一些我認爲非常基本的幫助。任何幫助,將不勝感激。我有一個我想要導入到Tcl的文本文件。我給你的文件的語法和我需要存儲它的方式:TCL創建列表

文本文件導入到Tcl的:

Singles 'pink granny fuji' 
Singles2 'A B C D E' 
Couples 'bread butter honey lemon cinnamon sugar' 
Couples2 'A1 A2 B1 B2 C1 C2 D1 D2' 

我想要的格式:

對於線1 & 2:

Singles 
[pink granny fuji] (3 single elements) 

Singles2 
[A B C D E] (5 single elements) 

對於線3 & 4:

Couples 
[bread butter 
honey lemon 
cinnamon sugar] (3 x 2 array) 

Couples2 
[A1 A2 
B1 B2 
C1 C2 
D1 D2] (4 x 2 array) 

導入文本文件在理論上可以有任意數量的元素,但行總是偶數個元素,因此它們是對,所以我知道每個循環都需要捕獲任意數量的元素。我知道代碼還需要從文本文件中去掉撇號。

我的那一刻真的很掙扎,非常感謝所有幫助都,謝謝:)

+0

只需要知道你所知道的。你知道tcl中的列表是什麼嗎?你知道關於foreach嗎?你熟悉正則表達式嗎? – slebetman

+0

我的第一個澄清問題:代碼應該如何決定使用第一種還是第二種輸出格式?這是因爲前面的字符串「Single」還是前面的字符串「Couple」,還是因爲數字指數是通過輸入數據計數的? –

+0

我的第二個澄清問題:單引號內單詞的規則是什麼?他們有沒有「特殊」字符 - 包括用作分隔符的嵌入空格 - 還是它們總是簡單的字母數字? –

回答

0

這裏是解決方案。它完美的作品。我希望你正在尋找類似的解決方案。

set handle [open "text_import" "r"] 
    set content [read $handle] 
    regsub -all {'} $content "" content 
    #set content [split [read $handle] \n] 
    set content [split $content \n] 

    foreach ele $content { 
     puts $ele 
     if {[regexp -nocase -- "(\[^ \]+) +(.*)" $ele - key val]} { 
      puts $key 
      if {[regexp -nocase -- "single" $key]} { 
       set val1 [split $val " "] 
       set arr($key) $val1 
      } elseif {[regexp -nocase -- "couple" $key]} { 
       set biggerList [list] 
       set val2 [split $val " "] 
       for {set i 0} {$i < [llength $val2]} {incr i 2} { 
        set tempList [list [lindex $val2 $i] [lindex $val2 [expr $i + 1]]] 
        lappend biggerList $tempList 
       } 
       set arr($key) $biggerList 
      } 
     } 
    } 


    parray arr 

+0

非常感謝您的幫助!你的代碼和語法幫助我編寫代碼,最後我使用readFile,字符串匹配,範圍和修剪來完成它。我甚至不需要正則表達式,因爲我的輸入文件非常簡單,但真的很高興看到該示例,並且我知道下次如何使用正則表達式。謝謝堆:) –

+0

偉大的,它已經幫助你。不要忘記+1,以便任何尋找這種解決方案的人都能看到它。 –

0

一個可能的解決方案。如果我們做出正確的定義,我們可以不加載文本文件作爲數據,而是將其作爲Tcl源文件加載。

proc Singles args { 
    set str [string trim [join $args] '] 
    puts "\[$str]" 
} 

proc Singles2 args { 
    set str [string trim [join $args] '] 
    puts "\[$str]" 
} 

proc Couples args { 
    set list [split [string trim [join $args] ']] 
    foreach {a b} $list { 
     lappend list2 "$a $b" 
    } 
    set str [join $list2 \n] 
    puts "\[$str]" 
} 

proc Couples2 args { 
    set list [split [string trim [join $args] ']] 
    foreach {a b} $list { 
     lappend list2 "$a $b" 
    } 
    set str [join $list2 \n] 
    puts "\[$str]" 
} 

source textfile.txt 

文檔: foreachjoinlappendlistprocputssetsourcesplitstring

+0

非常感謝您的幫助!這個想法絕對幫助了我,最後我用readFile,字符串匹配,範圍和修剪來做到這一點。再次感謝 :) –