【问题标题】:Inserting single curly braces to Tcl list elements将单个花括号插入 Tcl 列表元素
【发布时间】:2022-09-24 04:40:54
【问题描述】:

我有一个以这种形式包含多行的报告文件:

str1 num1 num2 ... numN str2

鉴于 (N) 跨行不同。这些数字代表坐标,所以我需要用花括号将每个点括起来:

{num1 num2} {num3 num4} 等等...

我试过这段代码:

set file_r [open file.rpt r]
set lines [split [read $file_r] \"\\n\"]
close $file_r
foreach line $lines {
    set items [split $line]
    set str1 [lindex $items 0]
    set str2 [lindex $items [expr [llength $items] - 1]]
    set box  [lrange $items 1 [expr [llength $items] - 2]]
    foreach coord $box {
        set index [lsearch $box $coord]
        set index_rem [expr $index % 2]
        if {index_rem == 0} {
            set box [lreplace $box $index $index \"{$coord\"]
        } else {
            set box [lreplace $box $index $index \"$coord}\"]
        }
    }
    puts \"box: $box\"
}

这给了我一个缺少右括号的语法错误。如果我尝试\"\\{$coord\",则会在$box 中输入反斜杠字符。

有什么想法可以克服这个吗?

  • 你能得到一个不成对的坐标值列表吗?将它们与lmap {a b} $coords {list $a $b} 配对很容易。
  • 我怎么得到它?我不知道点数,因为它因行而异。

标签: tcl


【解决方案1】:

您可以改进一些东西以获得更好和更简单的 Tcl 样式。

  1. 如果一行已经用空格分隔,通常不需要使用split 从一行形成一个列表。空格分隔的字符串几乎总是可以直接在列表命令中使用。 例外情况是字符串包含 {" 字符。
  2. lindexlrange 可以接受 endend-N 参数。

    这加上多纳尔使用lmap 的评论将导致:

    set file_r [open file.rpt r]
    set lines [split [read $file_r] "\n"]
    close $file_r
    foreach line $lines {
        set str1     [lindex $line 0]
        set str2     [lindex $line end]
        set numbers  [lrange $line 1 end-1]
        set boxes [lmap {a b} $numbers {list $a $b}]
        foreach box $boxes {
            puts "box: {$box}"
        }
    }
    

【讨论】:

  • 注意,只有当 OP 对file.rpt 的内容具有完全控制/权限时,您的第一个建议才有效。在 Tcl 中,不是所有空格分隔的字符串都是 Tcl 列表的有效字符串表示。因此,最好使用可以肯定返回有效列表的命令对$line 中的字符串进行预处理。 subst 为一,regexp -inline 一般推荐:set line [regexp -all -inline {\S+} $line]
  • 同意。当将字符串视为简单列表时,字符串中的花括号和双引号将成为问题。
  • 所以......您可能想添加到您的答案中?
  • 我最初说过带空格的字符串“几乎总是”可以像列表一样使用。当然,我会更新答案。我只是想指出,在 Tcl 中并不总是需要将字符串拆分为列表,这与 Python 中的字符串永远不能像列表一样对待。事实上,额外的空格,如[split "a b"] 将返回a {} {} {} {} {} {} b `
猜你喜欢
  • 1970-01-01
  • 2013-10-01
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多