Applescript:根据单词在序列中的出现次数编号列表 [英] 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.
任何帮助将不胜感激.
推荐答案
AppleScript 不是这项工作的正确工具,因此虽然以下解决方案有效,但它很慢.
AppleScript is not the right tool for this job, so while the following solution works, it is sloooow.
(为了获得更好的性能,您需要完整的哈希表功能,而 AppleScript 没有提供 - AppleScript 的 record
类由于无法动态地指定键而受到严重阻碍em>,在运行时,通过变量 - 但是存在第三方解决方案(例如,http://www.latenightsw.com/freeware/list-record-tools/)).
(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.
这篇关于Applescript:根据单词在序列中的出现次数编号列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!