Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

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

So I have this list of words:

{"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"}

I'd like each occurrence of a word to be numbered according to the number of times it has occurred in the sequence:

{"It", 1}, {"was", 1}, {"the", 1}, {"best", 1}, {"of", 1}, {"times", 1} {"it", 2}, {"was", 2}, {"the", 2}, {"worst", 1}, {"of", 2}, {"times", 2}, {"it", 3}, {"was", 3}, {"the", 3}, {"age", 1}, {"of", 3}, {"wisdom", 1}, {"it", 4}, {"was", 4}, {"the", 4}, etc.

Any help would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...