所以我有这个单词列表:
{"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"}
我希望每个单词的出现都按照它在序列中出现的次数进行编号:
{"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.
非常感谢任何帮助。
答案 0 :(得分:0)
AppleScript不是这项工作的合适工具,所以虽然以下解决方案有效,但它是懒散的。
(为了获得更好的性能,您需要AppleScript不提供的完整哈希表功能 - AppleScript的record
类因无法动态指定键而严重受限,在运行时,通过变量 - 存在第三方解决方案(例如,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.
答案 1 :(得分:0)
另一种方式......
# 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"}
set AppleScript's text item delimiters to linefeed
set inListLF to inList as text
set AppleScript's text item delimiters to {""}
set usedList to {}
set resultList to {}
repeat with aWord in inList
set aWord to contents of aWord
considering case
if aWord is not in usedList then
set end of usedList to aWord
set end of resultList to aWord & " - " & (do shell script "echo " & quoted form of inListLF & " | grep -o " & quoted form of aWord & " | wc -l")
end if
end considering
end repeat
set AppleScript's text item delimiters to linefeed
set resultList to resultList as text
set AppleScript's text item delimiters to {""}
return resultList