如何使用分隔符解析 tcl 中的文本文件? [英] How to parse a text file in tcl using separators?

查看:36
本文介绍了如何使用分隔符解析 tcl 中的文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式的文本文件

I have a text file of the format

35|46

36|49

37|51

38|22

40|1

39|36

41|4

我必须通过分隔符|"将文件读入数组其中左侧是数组的键,右侧是值.

I have to read the file into an array across the separator "|" where left side will be the key of the array and right side will be the value.

我使用了以下代码

foreach {line} [split [read $lFile] \n] {
    #puts $line
    foreach {lStr} [split $line |] {
        if { $lStr!="" } {
            set lPartNumber [lindex $lStr 0]
            set lNodeNumber [lindex $lStr 1]
            set ::capPartsInterConnected::lMapPartNumberToNodeNumber($lPartNumber) $lNodeNumber

        }
    }

}

close $lFile

我无法读取分隔符|"的左侧.怎么做?

I am not able to read the left side of the separator "|". How to do it?

与此类似:

35|C:\AI\DESIGNS\SAMPLEDSN50\BENCH_WORKLIB.OLB|R

36|C:\AI\DESIGNS\SAMPLEDSN50\BENCH_WORKLIB.OLB|R

我需要在不同的变量中分配所有三个字符串

I need to assign all three strings in different variables

推荐答案

您在 foreach 中犯了错误,其中 split 的结果将分配给循环变量lStr 一次只包含一个值导致失败.

You are making mistake in the foreach where the result of split will be assigned to a loop variable lStr where it will contain only one value at a time causing the failure.

使用 lassign,这可以轻松完成.

With lassign, this can be performed easily.

set fp [open input.txt r]
set data [split [read $fp] \n]
close $fp

foreach line $data {
    if {$line eq {}} {
        continue
    }
    lassign [split $line | ] key value
    set result($key) $value
}   
parray result

lassign [split "35|C:\\AI\\DESIGNS\\SAMPLEDSN50\\BENCH_WORKLIB.OLB|R" |] num userDir name
puts "num : $num"
puts "userDir : $userDir" 
puts "name : $name"

这篇关于如何使用分隔符解析 tcl 中的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆