tardy pigeon tardy pigeon - 1 year ago 93
AppleScript Question

Get paragraphs of a certain length in Applescript (and then do something with those paras)

Could I turn a list of songs into two separate lists: one where song titles are three words or less and one where they are four words or more? I want to take one list (as a variable) and run an action on it and then a separate action on the other list.

Here's as far as I got:

tell application "TextEdit"
tell the front document
set my_list to every paragraph whose (count of words) is 2
end tell
end tell

I can't seem to get the property of the number of words in each paragraph to work - I'm getting the error message: "TextEdit got an error: Can’t make 2671 into type reference."

It might help to explain what I am going to do next.

I'd get paragraphs of that list

set MySongs to paragraphs of my_list
-- read artist names (separated by newlines) from the file

And then add them to an iTunes playlist:

tell application "iTunes"
repeat with AnItem in MySongs -- get all tracks from each artist
set AnItem to (contents of AnItem)
if AnItem is not "" then try -- don't bother with empty names
set MyTracks to (location of file tracks of playlist "Music" whose name is AnItem)
--can also modify the above from "is" to "contains" or "_begins with_"
add MyTracks to NewPlaylist
on error errmess -- oopsie (not found, etc)
log errmess -- just log it
end try
end repeat
end tell

And then do a similar thing with the second list.

So: is it possible to get just the paragraphs from a text doc that are less than 4 words and make that into a variable to pass on in this fashion?



Answer Source

Here is an example of what I think you're trying to accomplish.

set mySampleText to "this is
my sample text data, lets see what happens if we
have different
length paragraphs"

set paras to paragraphs of mySampleText
set list1 to {}
set list2 to {}
repeat with apara in paras
    set apara to apara as string
    if (count of words in apara) is less than or equal to 2 then
        set end of list1 to apara
        set end of list2 to apara
    end if
end repeat

At the end of this script, you'll have two lists: list1 (the items with 2 words or less) and list2 (the items with 3 or more words).

On a side note, I would recommend against scripting TextEdit. There is really no reason to do so. You can just read your text file directly into your script and work with it.

For example...

set mySampleText to read file "Macintosh SSD:path:to:file.txt"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download