通过读取文本文件来查找行索引和单词索引

问题描述 投票:0回答:1

我刚刚开始学习Tcl,有人可以通过使用Tcl读取文本文件来帮助我找到特定单词的行索引和单词索引。

谢谢

tcl filereader tk file-read tcltk
1个回答
1
投票

正如评论中所提到的,您可以使用许多基本命令来解决问题。要将文件读入行列表,您可以使用opensplitreadclose命令,如下所示:

set file_name "x.txt"
# Open a file in a read mode
set handle [open $file_name r]
# Create a list of lines
set lines [split [read $handle] "\n"]
close $handle

通过使用for循环,incr和一组列表相关命令(如llengthlindexlsearch),可以在行列表中查找某个单词。 Tcl中的每个字符串都可以作为列表进行解释和处理。实现可能如下所示:

# Searching for a word "word"
set neddle "word"
set w -1
# For each line (you can use `foreach` command here)
for {set l 0} {$l < [llength $lines]} {incr l} {
  # Treat a line as a list and search for a word
  if {[set w [lsearch [lindex $lines $l] $neddle]] != -1} {
    # Exit the loop if you found the word
    break
  }
}

if {$w != -1} {
  puts "Word '$neddle' found. Line index is $l. Word index is $w."
} else {
  puts "Word '$neddle' not found."
}

在这里,脚本遍历这些行并在每一行中搜索给定的单词,就好像它是一个列表一样。对字符串执行list命令默认情况下按空格分割。当在一行中找到一个单词时(当lsearch返回非负索引时),循环停止。

另请注意,list命令将多个空格视为单个分隔符。在这种情况下,它似乎是一种理想的行为。在具有双空格的字符串上使用split命令将有效地创建“零长度字”,这可能产生不正确的字索引。

© www.soinside.com 2019 - 2024. All rights reserved.