【问题标题】:print dictionary keys and values in one column in tcl在 tcl 的一列中打印字典键和值
【发布时间】:2020-02-25 22:39:18
【问题描述】:

我是 tcl 脚本语言的新手。我正在使用 TCL 8.5 版。我通过 tcl 脚本读取文本文件并计算相似词的频率。我使用 for 循环和字典来计算相似的单词及其频率,但程序的输出如下所示: alpha 4 beta 2 gamma 1 delta 1 但是我想在每个键、字典的值对的列中打印它,或者我们可以说每个键、值对在输出中逐行打印。以下是我在 tcl 中的脚本及其最后的输出。

set f [open input.txt]
set text [read $f]
foreach word [split $text] {
    dict incr words $word
}
 puts $words

上述脚本的输出: 阿尔法 4 贝塔 2 伽马 1 德尔塔 1

【问题讨论】:

  • 如果您是 Tcl 新手,请考虑使用 Tcl 8.6。它与 8.5 一样容易获得,并且包括所有最新的好东西。除了得到实际支持。

标签: tcl


【解决方案1】:

你会这样做:

dict for {key value} $words {
    puts "$key $value"
}

阅读the dict documentation时,注意哪些子命令需要dictionaryVariable(如dict incr),哪些需要dictionaryValue(如dict for) p>


按照 Donal 的建议,为了获得良好的格式,这里有一个非常简洁的方法:

set maxWid [tcl::mathfunc::max {*}[lmap w [dict keys $words] {string length $w}]]
dict for {word count} $words {puts [format "%-*s = %s" $maxWid $word $count]}

或者,查看parray 命令的源代码以获得更多灵感:

parray tcl_platform  ;# to load the proc
info body parray

【讨论】:

  • 可能首先遍历字典的键 (foreach key [dict keys $words] ...) 以确定列的最大宽度。
猜你喜欢
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多