[Solved] Applescript: number list of words according to their occurrence in the sequence

[ad_1]

AppleScript is not the right tool for this job, so while the following solution works, it is sloooow.

(For better performance, you’d need full hash-table functionality, which AppleScript doesn’t provide – AppleScript’s record class is severely handicapped by the inability to specify keys dynamically, at runtime, via variables – third-party solutions exist, though (e.g., http://www.latenightsw.com/freeware/list-record-tools/)).

# Helper handler: Given a search word, returns the number of times the word 
# already occurs in the specified list (as the first sub-item of each list item).
on countOccurrences(searchWrd, lst)
  local counter
  set counter to 0
  repeat with wordNumPair in lst
    if item 1 of wordNumPair is searchWrd then
      set counter to counter + 1
    end if
  end repeat
  return counter
end countOccurrences

# Define the input list.
set inList to {"It", "was", "the", "best", "of", "times", "it", "was", "the", "worst", "of", "times", "it", "was", "the", "age", "of", "wisdom", "it", "was", "the", "age", "of", "foolishness", "it", "was", "the", "epoch", "of", "belief"}

# Initialize the output list.
set outList to {}

# Loop over the input list and build the output list incrementally.
repeat with wrd in inList
  # Note that `contents of` returns the string content of the list item
  # (dereferences the object specifier that `repeat with` returns).
  set outList to outList & {{contents of wrd, 1 + (my countOccurrences(contents of wrd, outList))}}
end repeat

# outList now contains the desired result.

2

[ad_2]

solved Applescript: number list of words according to their occurrence in the sequence