如何计算实时代码中的出现次数?

How to count occurance in livecode?

我需要从字段 "MytextField" 中计算单词在数组中出现的次数。该数组由 9000 多行组成,字段 "MytextField" 中的文本由 10000 多行组成。我正在使用以下代码,它工作正常但需要很多时间。

put the number of lines of (the keys of myArray) into myArrayL
   repeat with i = 0 to myArrayL
      put  myArray[i] into k 
      split k by colon
      put k[1] into searchStr
      put k[2] into replaceStr
      repeat for each line iword in Tex
         if  iword contains searchStr then
            add 1 to tmp
            put tmp & "                 " & searchStr & cr into sam
         end if
         --delete word iword of Tex
         if  iword contains replaceStr then
            add 1 to tmp1
            put tmp1 & "                 " & replaceStr & cr into sam1
         end if
         --delete word iword of Tex
      end repeat
      put sam after slu
      put 0 into tmp
      put "" into sam
      put sam1 after slu1
      put 0 into tmp1
      put "" into sam1
   end repeat
answer slu1
answer slu

有什么减少时间消耗的方法吗? 如何更快速地更改此代码

试试 repeat for each element 结构。在这种情况下,它通常比 repeat with i = x to y 形式更快。

repeat for each element thisElement in myArray
   # your loop logic here
end repeat

尝试使用偏移量,这应该比检查每个单词更快:

put fld "MytextField" into tText
set the itemdel to colon
repeat for each element e in myArrayL
  put item 1 of e into searchStr
  put 0 into tSkip
  repeat
    get wordOffset(searchStr,tText,tSkip)
    if it = 0 then exit repeat
    add it to tSkip
    add 1 to tCountArray[searchStr]
  end repeat
end repeat

对搜索词进行计数并将计数放入数组中。如果您还需要计算替换词,您可以稍微改变它并再次 运行 它。不要计算同一重复循环中的搜索词和替换词,您会得到不正确的结果。我不知道这是否会比您的原始脚本快得多,因为如果您想要搜索和替换字数,重复循环必须 运行 两次。

数组制作完成后,可以使用combine命令快速显示计数。