Sort string by values in text file using applescript - string

I'm trying to build an applescript to sort tags in the Genre field of a music file in iTunes.
I'm using a semi-colon separated list for the Genre field, like this: Rock; Art Rock; Female Vocalists
The string I want to sort is named genreList in my script:
{"Art Rock", "Female Vocalists", "Rock"}
My preferred tag order is listed as sortList:
{"Rock", "Dance", "Art Rock", "New Wave", "Female Vocalists", "Male Vocalists"}
I want the items in genreList to sort according to sortList, like this:
{"Rock", "Art Rock", "Female Vocalists"}
How do I sort the first list using the second list? I've searched here and on Google, but as I am a scripting novice I'm not even sure I'm searching for the right terms.

Try this, select one or multiple tracks in iTunes and run the script.
If the separator is supposed to be semicolon + space, please change the second property line.
If the genre property does not contain the separator, nothing will be changed.
If a genre does not match the items in the sorted list it will be appended at the end.
property sortedGenreList : {"Rock", "Dance", "Art Rock", "New Wave", "Female Vocalists", "Male Vocalists"}
property separator : ";"
tell application "iTunes" to set selectedItems to (get selection)
if selectedItems is {} then
display dialog "Nothing selected" buttons {"Cancel"} default button 1
end if
set {TID, text item delimiters} to {text item delimiters, separator}
repeat with aTrack in selectedItems
set orderedGenreList to {}
set nonOrderableGenres to {}
tell application "iTunes" to set trackGenreList to text items of (get genre of aTrack)
if (count trackGenreList) > 1 then
repeat with aGenre in trackGenreList
if sortedGenreList does not contain aGenre then set end of nonOrderableGenres to contents of aGenre
end repeat
repeat with aGenre in sortedGenreList
if trackGenreList contains aGenre then
set end of orderedGenreList to contents of aGenre
end if
end repeat
set orderedGenres to (orderedGenreList & nonOrderableGenres) as text
tell application "iTunes" to set genre of aTrack to orderedGenres
end if
end repeat
set text item delimiters to TID
If you want to use a text file with a genre per line replace the first property line with
set sortedGenreList to paragraphs of (read (choose file))

Related

Extract line number with checkbox

how can i extract line with check box. In my stuck i have
text fld: "news",
group of checkbox: "Checkboxs",
checkbox: "Check 1 - Check 10",
button: "button" and a destination fld "Lower".
Now i went:
1) when i select multiple checkbox, checkbox will extract multiple line form text fld "news".
2) when i press button, button get text from fld "news" through checkbox and put it to fld "lower" horizontally one by one.
I have upload my project here you may check it.
Plz advice.
I think you want something like:
on mouseUp
local tLower, tNews, tLineNumber
put field "news" into tNews
repeat for each line tID in the childControlIDs of group "Checkboxs"
-- checkboxes named "Check <linenumber>"
put word 2 of the short name of control id tID into tLineNumber
put line tLineNumber of tNews & return after tLower
end repeat
delete the last char of tLower
put tLower into field "lower"
end mouseUp

Convert AppleScript List into String

I was wondering if there is a short way to convert an AppleScript list into a string separating each item. I can achieve this in a way which is more lengthy that I would like, so I wondered if there is a simple way to achieve this. Basically, I would like to take a list such as {1,2,3} and convert it in to a string "1, 2, 3". I can do something like below, but that results in a comma following the resulting string:
set myList to {"1.0", "1.1", "1.2"}
set Final to ""
if (get count of myList) > 1 then
repeat with theItem in myList
set Final to Final & theItem & ", "
end repeat
end if
There is a short way, it's called text item delimiters
set myList to {"1.0", "1.1", "1.2"}
set saveTID to text item delimiters
set text item delimiters to ", "
set Final to myList as text
set text item delimiters to saveTID
Create your own snippet for this
Convert a list to a string is so frequent that you better create a subroutine.
on list2string(theList, theDelimiter)
-- First, we store in a variable the current delimiter to restore it later
set theBackup to AppleScript's text item delimiters
-- Set the new delimiter
set AppleScript's text item delimiters to theDelimiter
-- Perform the conversion
set theString to theList as string
-- Restore the original delimiter
set AppleScript's text item delimiters to theBackup
return theString
end list2string
-- Example of use
set theList to {"red", "green", "blue"}
display dialog list2string(theList, ", ")
display dialog list2string(theList, "\n")

Read CSV file as Array with AppleScript

I would like to read in a CSV file in as a 2D array and then return it back to a CSV file.
Let's say that this is my CSV file. It is an excel file and the | implies the adjacent cell:
family | type
Doctor | Pediatrics
Engineer | Chemical
From what I understand, there are no arrays on applescript, just lists and records. If it would be better to do this with a XLSX file, please let me know.
Nigel's CSV-to-list converter is the best I have seen ...
http://macscripter.net/viewtopic.php?pid=125444#p125444
For your example, use these settings:
set csvText to "family | type
Doctor | Pediatrics
Engineer | Chemical"
csvToList(csvText, {separator:"|"}, {trimming:true})
v2
set csvText to read "/Users/user1385816/Desktop/yourfile.csv"
csvToList(csvText, {}, {trimming:true})
An array is just a list in applescript, so you want a 2d array or a list-of-lists in applescript-speak. If you understand applescript's text item delimiters then your task is just simple manipulation to convert strings into lists and vice versa. So I wrote you a couple handlers to make the task easy for you; textToTwoDArray() and twoDArrayToText(). This first example shows how to convert your string into a list-of-lists using textToTwoDArray().
NOTE: you have to be careful of the line endings in a text file because they can be either a carriage return (character id 13) or a line feed (character id 10). You can see I used character id 10 in my code but if you aren't getting the proper results try "13".
set fileText to "family | type
Doctor | Pediatrics
Engineer | Chemical"
textToTwoDArray(fileText, character id 10, " | ")
on textToTwoDArray(theText, mainDelimiter, secondaryDelimiter)
set {tids, text item delimiters} to {text item delimiters, mainDelimiter}
set firstArray to text items of theText
set text item delimiters to secondaryDelimiter
set twoDArray to {}
repeat with anItem in firstArray
set end of twoDArray to text items of anItem
end repeat
set text item delimiters to tids
return twoDArray
end textToTwoDArray
And here's how to convert a list-of-lists back into your string using twoDArrayToText().
set twoDArray to {{"family", "type"}, {"Doctor", "Pediatrics"}, {"Engineer", "Chemical"}}
twoDArrayToText(twoDArray, character id 10, " | ")
on twoDArrayToText(theArray, mainDelimiter, secondaryDelimiter)
set {tids, text item delimiters} to {text item delimiters, secondaryDelimiter}
set t to ""
repeat with anItem in theArray
set t to t & (anItem as text) & mainDelimiter
end repeat
set text item delimiters to tids
return (text 1 thru -2 of t)
end twoDArrayToText
So now all you have to do is figure out how to read and write to a text file with applescript. Good luck ;)
If your question is just about modeling your CSV data in AppleScript, the solution is to use a list of records like this:
set csvData to {{family:"Doctor", type:"Engineer"}, {family:"Engineer", type:"Chemical"}}
you can then read that out again inside a repeat with aRow in csvData loop.
A technical note: AppleScript lists are implemented as vectors, meaning they are ordered and can be accessed by numerical index (beginning at index 1) – they behave much like an array in most other languages.

How can I add commas to a string of numbers in Applescript?

In Applescript I have a string of single digit numbers:
0123456789
I want to go through that string and add a comma between each number, so it would show:
0,1,2,3,4,5,6,7,8,9
How can I do this with Applescript?
Notes
I want both the input and output to be of type "string" - not list.
The numbers will always be single digit numbers.
You can use a handy feature called AppleScript's text item delimiters, which allows you to break up (or "parse" in computer jargon) text into segments, and then extract data from those segments. They are the separators of text items in a piece of text. A simple example:
set prevTIDs to AppleScript's text item delimiters
set theString to "Don't-eat-the-yellow-snow"
set AppleScript's text item delimiters to "-" --tell AppleScript to break up strings at each occurrence of a hyphen '-' in a given string
set these_items to every text item of theString
//--> {"Don't", "eat", "the", "yellow", "snow"}
set AppleScript's text item delimiters to prevTIDs
return these_items
It is always considered good practice when working with text item delimiters to restore the original delimiters; once you change the delimiters, they will globally affect the running environment until the process is closed and restarted.
Another use for text item delimiters is replacing words or characters in a given string:
set prevTIDs to AppleScript's text item delimiters
set theString to "Don't eat the yellow snow"
set AppleScript's text item delimiters to "yellow" --the word you want to replace
set temp to every text item of theString
//--> {"Don't eat the", "snow"}
set AppleScript's text item delimiters to "pink" --the replacement word
set theString to temp as string
set AppleScript's text item delimiters to prevTIDs
return theString
//--> "Don't eat the pink snow"
However, note that this replaces every occurrence of the word "yellow". The reason I'm saying this is consider the following string:
If someone added one plus one, what would be the result?
If you wanted to replace the word "one" with the word "two", you would have to be sure to precede "two" with a space when creating the new delimiter, or your resulting string would be the following:
If sometwo added two plus two, what would be the result?
What you're trying to do is basically replacing empty strings with commas. All you need to do is follow these simple steps to do this:
Create a variable to store the current delimiters in
Create a variable to store your string in
Change the delimiter to an empty string ""
Coerce your string into a list (i.e. set the list to every text item of yourString)
Change the delimiter to a comma ,
Coerce your newly created list back into a string (i.e. set yourString to list as string)
Restore the old delimiters
return your string
The resulting code:
set prevTIDs to AppleScript's text item delimtiers
set myString to "0123456789"
set AppleScript's text item delimiters to ""
set the_list to every text item of myString
set AppleScript's text item delimiters to ","
set myString to the_list as string
set AppleScript's text item delimiters to prevTIDs
return myString
Happy coding! :)
Something like this?
set theNumber to "3452678190"
set AppleScript's text item delimiters to ","
set theItems to every character of theNumber as string
set AppleScript's text item delimiters to ""
return theItems

Applescript error when trying to reference last paragraph of a string -1728

My code:
tell application "iTunes"
set ofi to fixed indexing
set fixed indexing to true
set sel to selection
repeat with i from 1 to (count sel)
tell (item i of my sel)
set fileLoc to the location as Unicode text
set fileLoc to my findAndReplace(":", "
", fileLoc)
--display dialog return & fileLoc buttons {"Ok"} default button 1 with icon 0
--Show Name
set showName to paragraph -3 of fileLoc
set show to (showName as text)
--Season #
set seasonNum to the last word of paragraph -2 of fileLoc
try
set season number to (seasonNum as number)
end try
--Episode #
--*****ERROR HAPPENS HERE*****
set test to the first word of the last paragraph
set episodeNum to (the word 2 of paragraph -1)
--set episode number to episodeNum as number
--Episode name
set episodeName to characters 4 thru -5 of paragraph -1 of fileLoc
set name to episodeName as text
--Video Kind
set video kind to TV show
end tell
end repeat
set fixed indexing to ofi
end tell
on findAndReplace(tofind, toreplace, TheString)
set ditd to text item delimiters
set res to missing value
set text item delimiters to tofind
repeat with tis in text items of TheString
if res is missing value then
set res to tis
else
set res to res & toreplace & tis
end if
end repeat
set text item delimiters to ditd
return res
end findAndReplace
and I get:
error "iTunes got an error: Can’t get word 1 of last paragraph of file track id 7141 of user playlist id 5157 of source id 69." number -1728 from word 1 of last paragraph of file track id 7141 of user playlist id 5157 of source id 69
The text I'm trying to parse looks like:
Users
christopher
TV Shows
How I Met Your Mother
Season 5
01 Definitions.m4v
Turns out I needed "of fileLoc" in there to make it work.

Resources