文本文件中每三行的Applescript列表

时间:2011-07-14 01:28:36

标签: applescript

说我有一个像这样的文本文件:

apples
pencils
juice
apricots
John Doe
the string system is amazing

我想为文本文件中的每3个项目创建一个列表,如此(当然是字符串):

item list 1={apples, pencils, juice}
item list 2={apricots, John Doe, the string system is amazing}

但是,文本文件将包含超过6行和不同的行文本,因此 不能 具体如下:

set line1 of myfile to item 1 of mylist 
set line2 of myfile to item 2 of mylist 
set line3 of myfile to item 3 of mylist

set line4 of myfile to item 1 of mySecondlist 
set line5 of myfile to item 2 of mySecondlist 
set line6 of myfile to item 3 of mySecondlist 

1 个答案:

答案 0 :(得分:4)

试试这个。代码应该是自我解释的,但如果您需要帮助,请提出问题。

-- get the text from the file
set theFile to choose file
set theText to read theFile

-- turn the text into a list so we can loop over it
set theTextList to paragraphs of theText

-- put every 3 items into a list and add it to the finalList variable
set listCount to count of theTextList
set finalList to {}
repeat with i from 1 to listCount by 3
    if (i + 2) is not greater than listCount then
        set end of finalList to items i thru (i + 2) of theTextList
    else
        set end of finalList to items i thru listCount of theTextList
    end if
end repeat

-- show the list of lists result
return finalList

如果您的文件包含您显示的值,则结果为...

{{"apples", "pencils", "juice"}, {"apricots", "John Doe", "the string system is amazing"}}