我有一个名为 file1.txt 的文件,其内容如下所述
file1.txt 的内容:
AND 60
NAND 20
OR 30
SUN 90
SIN 10
SIM 80
EW 25
NEW 85
PHEW 55
因此,文件总共有 9 行,其中有两个空行,数据每组包含 2 列和 3 行,并且有 3 个这样的组,它们之间有两个空行。编写 Tcl 代码来读取 file1.txt 可以使用哈希对这 3 组进行排序并按升序打印 3 组。如下所示 输出:
NAND 20
OR 30
AND 60
SIN 10
SIM 80
SUN 90
EW 25
PHEW 55
NEW 85
当您编写代码时,请使其具有弹性和可扩展性,以适应包含数百个此类组的数据输入,并且不要将其限制为仅包含 3 个条目的 3 个组
我已经尝试过下面的代码,但这没有给出正确的输出
# Function to read the file and organize data into a hash
proc readAndOrganizeDataFromFile {filename} {
set fileId [open $filename]
set data [read $fileId]
close $fileId
set groups [split $data "\n\n"]
set hashTable [dict create]
foreach group $groups {
set lines [split $group "\n"]
foreach line $lines {
if {$line eq ""} {
continue ;# Skip empty lines
}
set parts [split $line]
set key [lindex $parts 0]
set value [lindex $parts 1]
dict lappend hashTable $key $value
}
}
return $hashTable
}
# Function to sort and print the hash table
proc sortAndPrintHash {hashTable} {
set sortedKeys [lsort -dictionary [dict keys $hashTable]]
foreach key $sortedKeys {
set values [dict get $hashTable $key]
set output [join $values " "]
puts $output
}
}
# Example usage
set filename "file1.txt"
set hashTable [readAndOrganizeDataFromFile $filename]
sortAndPrintHash $hashTable
有几个问题:
split
命令: split string ?splitChars?
Returns a list created by splitting string at each character that is in
the splitChars argument.
当
splitChars
设置为"\n\n"
时,表示将字符串按每个“分割”
“...不是连续两个 \n
字符。splitChars
是一组单独的字符,而不是精确的字符串。
您没有保留原始组的原始数据。
所有数据都会进入一个大而扁平的字典中。没办法再分组举报了。
您正在按键而不是值对数据进行排序。
我的建议是将原始文件作为字典读取,其中键是组号,值是列表的列表。然后使用
lsort -index 1
对字典的每个值进行排序,以便按每个列表中的第二个元素对每个值进行排序。
proc readAndOrganizeDataFromFile {filename} {
set fileId [open $filename]
set data [read $fileId]
close $fileId
set hashTable [dict create]
set lines [split $data "\n"]
set group_num 0
foreach line $lines {
if {$line eq ""} {
incr group_num
continue
}
# key = group_num
# value = list of lines
dict lappend hashTable $group_num $line
}
return $hashTable
}
proc sortAndPrintHash {hashTable} {
set sortedKeys [lsort -dictionary [dict keys $hashTable]]
foreach key $sortedKeys {
set values [dict get $hashTable $key]
set sorted_value [lsort -dictionary -index 1 $values]
foreach value $sorted_value {
puts $value
}
puts ""
}
}
# Example usage
set filename file1.txt
set hashTable [readAndOrganizeDataFromFile $filename]
sortAndPrintHash $hashTable