首页 > 解决方案 > AppleScript:将 40 段分成 4 段的 10 段

问题描述

从本质上讲,我从一个 excel 文件中获取一列数据并将其分成小组。所以:

10

20

30

40

50

60

ETC...

分为:

“10、20、30、40”

“50、60、70、80”

ETC

使用 AppleScript,我假设你会嵌套循环,类似于:

tell application "TextEdit"
set theText to text of front document as string
set myParas to every paragraph of theText
set myNum to the number of paragraphs of theText

repeat myNum times

    repeat 4 times

    end repeat

 end repeat
end tell

我将每月更新一次以数字和文本列形式出现的数据。我可以很容易地删除所有文本,只是想知道如何将段落分解或合并成更小的块的原理。

由于许多复杂的原因,我坚持使用 AppleScript 和 textEdit,因此不能选择其他替代方法(例如使用 javascript 或 textWrangler 或其他方法进行按摩)。

此外,也许 textEdit 可以自己执行此操作,但我将使用的脚本将基于上述结果进行许多其他操作,因此 AppleScript 必须完成所有繁重的工作。

标签: stringtextapplescriptparagraph

解决方案


您可以在重复循环中指定步长,因此您可以执行以下操作:

tell application "TextEdit" to set theText to text of front document
set paras to paragraphs of theText
set step to 4 -- number of items in a group
repeat with i from 1 to (count paras) by step
    try
        buildString(items i thru (i + step - 1) of paras)
    on error errmess number errnum -- index out of bounds
        log errmess
        if errnum is -128 then error number -128 -- quit
        buildString(items i thru -1 of paras) -- just to the end
    end try
end repeat

to buildString(someList)
    set tempTID to AppleScript's text item delimiters
    set AppleScript's text item delimiters to ", "
    set output to someList as text
    set AppleScript's text item delimiters to tempTID
    display dialog output -- show it
    return output
end buildString

推荐阅读