开发者

Applescript list for every three lines in a text file

Say I have a text file like so:

apples
pencils
juice
apricots
John Doe
the string system is amazing

I want a list created for every 3 items in the text file like so (as strings of course):

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

However, the text file will contain more than 6 lines and different text of the lines so it cannot be specific like:

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 


Try this. The code should be self explanatory, but if you need help ask questions.

-- 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

If your file contained the values you showed, here's the result...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜