Список Applescript для каждых трех строк в текстовом файле - PullRequest
1 голос
/ 14 июля 2011

Скажем, у меня есть текстовый файл, например, так:

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 Ответ

4 голосов
/ 14 июля 2011

Попробуй это. Код должен быть понятен, но если вам нужна помощь, задавайте вопросы.

-- 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"}}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...