【问题标题】:To find line index and word index by reading a text file通过读取文本文件查找行索引和单词索引
【发布时间】:2019-02-11 03:44:40
【问题描述】:

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

谢谢

【问题讨论】:

  • 自从你学习以来,你的尝试是什么?
  • 您要调查的命令:whilegetssplitopencloseforincr
  • 感谢您的帮助

标签: tcl filereader tk file-read tcltk


【解决方案1】:

如 cmets 中所述,您可以使用许多基本命令来解决您的问题。要将文件读入行列表,您可以使用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 返回一个非负索引时)。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2017-04-04
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    相关资源
    最近更新 更多