使用tcl计算文件中特定单词的数量

时间:2016-08-19 12:39:20

标签: tcl

我有一个文件,其中的内容按以下顺序排列:

This is not right
Right statement it is
This is incorrect
Give right expression

如何使用tcl脚本找到“正确”一词的计数?由于它不在列表中,我无法统一这些陈述并采用表达式。 哪些命令适合使用lsort或regexp?

1 个答案:

答案 0 :(得分:2)

假设文本位于文件“myfile.txt”中,我们可以将文本复制到text变量中:

set f [open myfile.txt]
set text [read $f]
# => This is not right
# => Right statement it is
# => This is incorrect
# => Give right expression
close $f

内联搜索忽略大小写的所有匹配项会给出一个我们可以计算的单词列表:

llength [regexp -inline -all -nocase right $text]
# => 3
llength [regexp -inline -all -nocase this $text]
# => 2

(这是正确的:文中有三个“右”和两个“这个”。)

这将完成同样的工作,因为我们实际上对单词列表不感兴趣,只是单词数量:

regexp -all -nocase this $text

这些简单的正则表达式在其他单词中没有出现任何单词时起作用,例如“bright”中的“right”或“empathize”中的“this”。如果这种误报是可能的,那么正则表达式需要更复杂。 \m\M约束可分别用于标记单词的开头和结尾:

regexp -all -nocase {\mright\M} $text

这将匹配“正确”但不是“明亮”或“明快”。

另一种计算文本中每个单词频率的方法是使用字典结构:

set words {}
foreach word [split [string tolower $text]] {
    dict incr words $word
}

现在,我们可以查询结构中单个词的频率:

dict get $words right
# => 3
dict get $words this
# => 2

或者查看频率表:

set words
# => this 2 is 3 not 1 right 3 statement 1 it 1 incorrect 1 give 1 expression 1

更新句子中最后一个单词的词频。

你写了“声明”,但我认为你的意思是“句子”。如果这是错误的,你需要告诉我如何识别声明的结束。

在句子末尾定义一个单词作为非空白字符序列,后跟一个文字句点字符,这些单词的频率可以这样计算:

set words {}
foreach word [regexp -inline -all {\S+(?=\.)} [string tolower $text]] {
    dict incr words $word
}

然后按上述步骤进行。

文档: closedictforeachllengthopenreadregexpsetsplitstringSyntax of Tcl regular expressions

相关问题