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

时间:2019-02-11 03:44:41

标签: tcl filereader tk file-read tcltk

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

谢谢

1 个答案:

答案 0 :(得分: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)来找到行列表中的某个单词# 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." } 。 Tcl中的每个字符串都可以解释为列表。该实现可能如下所示:

lsearch

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

还请注意,list命令将多个空格视为单个分隔符。在这种情况下,这似乎是一种期望的行为。在具有双倍空格的字符串上使用$args = array( 'post_type' => 'product','' ); $products = get_posts( $args ); foreach ($products as $product) { $data = get_post_meta($product->ID); $pr['regular_price'] = $data['_regular_price']['0']; $pr['sale_price'] = $data['_sale_price']['0']; 命令将有效地创建“零长度单词”,这可能会产生错误的单词索引。

相关问题