Vai al contenuto


Applescript per iTunes


  • Please log in to reply
13 risposte a questa discussione

#1 Signor D

Signor D

    Melina d'Oro

  • Staff
  • 3264 Messaggi:
  • Sesso:Maschietto
  • Località:Parigi

Inviato 07 gennaio 2012 - 21:53

Grazie a mac.appstorm.net ho scoperto un uso bellissimo degli Applescript per iTunes:

http://mac.appstorm....th-applescript/

Mi sono detto che a partire da uno degli script esistenti, questo, si poteva crearne uno che trasformasse le maiuscole in minuscole: in italiano (tra le altre lingue) sostantivi e verbi non hanno diritto alla maiuscola più che non in una frase normale. Mi sono detto che sarebbe stato facile introdurre questo minimo cambiamento, eppure, come diceva kkk, non è così semplice (soprattutto quando non si è capaci).

Vorrei copiare solo la parte utile, ma non sono sicuro di quale sia, quindi copio tutto.

--===========LIST OF TAGS TO MODIFY===========--
--These are the tags that will be selected by default.
property my_tags_to_modify : {"name", "album"}

--This is the complete list of tags -->which you shouldn't modify unless you know what you are doing 8>)
property tags_to_modify : {"name", "album", "artist", "composer", "grouping", "show"}

--===========LIST OF LOWERCASE WORDS===========--
--These are the words that will remain lowercase, unless they begin or end the title.
property lowercase_words : {"a", "an", "and", "at", "but", "by", "for", "in", "nor", "of", "on", "or", "so", "the", "to", "with"}
--Feel free to add these: "amid", "anti", "as", "down", "into", "like", "near", "off", "onto", "out", "over", "past", "per", "plus", "save", "some", "than", "till", "up", "upon", "via", "yet"

--===========LIST OF UNMODIFIED WORDS===========--
--These are the words that won't be modified at all. It's a good place to put all-uppercase words.
property unmodified_words : {"FM", "USA", "WDPK", "OYF’N", "UR", "TV", "MGM", "DVD", "ABC", "CD", "USSR", "CA", "WA", "NY", "NYC", "LP", "EP", "VHS", "UK", "GB", "'Bout", "'Cause", "o'", "'n'", "n'", "McCartney", "vs.", "de", "feat.", "Pi-hsien", "von", "van"}

--===========LIST OF TRAILING CHARACTERS===========--
--Any word trailed by a character in this list will be title cased. (ie. "a song" (with a remix)  -> "A Song" (With a Remix))
property other_chars : "_!\"$%&/()=¿?@¡|#¢∞“”[]{}*-+•«»—´`ºª…:;."



--===========NO NEWBIE-USER-MODIFIABLE PARTS BELOW===========--

property lowercase_match : false
property unmodified_Match : false
property other_chars_match : false
property my_tags : my_tags_to_modify
property myTitle : "Proper English Title Capitalization"

global aWord, newWord

tell application "iTunes"
	set mySelectedTracks to selection
	if mySelectedTracks is not {} then
		set old_fi to fixed indexing
		set fixed indexing to true
		set songs_selected to (count mySelectedTracks)
		
		if songs_selected = 1 then
			set songs_selected_message to "Brani selezionati: " & songs_selected & "." as text
		else
			set songs_selected_message to "Brani selezionati: " & songs_selected & "." as text
		end if
		
		set choice to button returned of (display dialog songs_selected_message & return & return & "Che facciamo?" buttons {"Lascia stare", "Configura…", "Modifica"} default button 3 with icon 1 with title myTitle)
		
		if choice = "Configura…" then
			set my_tags_to_modify to (choose from list tags_to_modify with prompt "Scegli gli attributi che vuoi modificare (quelli non selezionati verranno ignorati tags will be ignored):" default items my_tags_to_modify with title myTitle with multiple selections allowed without empty selection allowed)
			if my_tags_to_modify is false then
				set my_tags_to_modify to my_tags
				run me
			else
				display dialog "Possiamo andare." buttons {"Lascia stare", "Modifica"} default button 2 with title myTitle
			end if
		end if
		
		repeat with selected_tag in my_tags_to_modify --Check which tags are to be modified.
			repeat with aTrack in mySelectedTracks
				set selected_tag to selected_tag as text
				
				if selected_tag = "name" then set theTitle_as_List to (my text_to_list(aTrack's name, space))
				if selected_tag = "artist" then set theTitle_as_List to (my text_to_list(aTrack's artist, space))
				if selected_tag = "composer" then set theTitle_as_List to (my text_to_list(aTrack's composer, space))
				if selected_tag = "album" then set theTitle_as_List to (my text_to_list(aTrack's album, space))
				if selected_tag = "show" then set theTitle_as_List to (my text_to_list(aTrack's show, space))
				if selected_tag = "grouping" then set theTitle_as_List to (my text_to_list(aTrack's grouping, space))
				
				set newTitle to {}
				set last_item to (count theTitle_as_List)
				set word_counter to 1
				
				repeat with aWord in theTitle_as_List
					set newWord to ""
					repeat with my_unmodified_Match in unmodified_words
						--Check if any of the words belong to the list of unmodified words.
						if (my_unmodified_Match as text) = (aWord as text) then
							set unmodified_Match to true
							exit repeat
						end if
					end repeat
					if unmodified_Match then
						--Unmodify matching words in unmodified_words list (actually just copy the word from the list).
						set newWord to my_unmodified_Match as text
						set unmodified_Match to false
					else if (word_counter = 1) then
						--Capitalize first word in title.
						my SetCase(aWord)
					else
						--For words not beginning or ending the title (middle words).
						repeat with my_lowercase_Match in lowercase_words
							--Check if any of the middle words belong to the list of lowerase words.
							if (my_lowercase_Match as text) = (aWord as text) then
								set lowercase_match to true
								exit repeat
							end if
						end repeat
						if lowercase_match then
							--Lowercase matching words in lowercase_words list (actually just copy the word from the list).
							set newWord to my_lowercase_Match as text
							set lowercase_match to false
						else
							--Capitalize the rest of the words.
							my SetCase(aWord)
						end if
					end if
					copy newWord to end of newTitle
					set word_counter to (word_counter + 1)
				end repeat
				
				-->> log (my list_to_text(newTitle, space)) -- de-bugging only
				
				try
					if selected_tag = "name" then set aTrack's name to my list_to_text(newTitle, space)
					if selected_tag = "artist" then set aTrack's artist to my list_to_text(newTitle, space)
					if selected_tag = "composer" then set aTrack's composer to my list_to_text(newTitle, space)
					if selected_tag = "album" then set aTrack's album to my list_to_text(newTitle, space)
					if selected_tag = "show" then set aTrack's show to my list_to_text(newTitle, space)
					if selected_tag = "grouping" then set aTrack's grouping to my list_to_text(newTitle, space)
				end try
				
			end repeat
		end repeat
		
		copy old_fi to fixed indexing
		display dialog return & return & "Tutto fatto!" buttons {"Bene"} default button 1 with icon 1 with title myTitle giving up after 5
	else
		display dialog "Non hai selezionato alcun brano." buttons {"Lascia stare"} default button 1 with icon 0
	end if
end tell

--The handler taking care of the casing of words.
on SetCase(aWord)
	repeat with j from 1 to (length of aWord)
		if other_chars contains (character j of aWord) then
			set j to (character j of aWord)
			set newWord to newWord & j
			set other_chars_match to true
		else if other_chars_match then
			set j to (character j of aWord)
			if ((id of j) is greater than 96) and ((id of j) is less than 123) then
				set newWord to newWord & (character id ((id of j) - 32))
			else if ((id of j) is greater than 64) and ((id of j) is less than 91) then
				set newWord to newWord & j
			else
				set newWord to newWord & j
			end if
			set other_chars_match to false
		else if (j = 1) then
			set j to (character j of aWord)
			if ((id of j) is greater than 96) and ((id of j) is less than 123) then
				set newWord to newWord & (character id ((id of j) - 32))
			else
				set newWord to newWord & j
			end if
		else
			set j to (character j of aWord)
			if ((id of j) is greater than 96) and ((id of j) is less than 123) then
				set newWord to newWord & j
			else if ((id of j) is greater than 64) and ((id of j) is less than 91) then
				set x to (character id ((id of j) + 32))
				set newWord to newWord & x
			else
				set newWord to newWord & j
			end if
		end if
	end repeat
end SetCase

on text_to_list(txt, delim)
	set saveD to AppleScript's text item delimiters
	try
		set AppleScript's text item delimiters to {delim}
		set theList to every text item of txt
	on error errStr number errNum
		set AppleScript's text item delimiters to saveD
		error errStr number errNum
	end try
	set AppleScript's text item delimiters to saveD
	return (theList)
end text_to_list

on list_to_text(theList, delim)
	set saveD to AppleScript's text item delimiters
	try
		set AppleScript's text item delimiters to {delim}
		set txt to theList as text
	on error errStr number errNum
		set AppleScript's text item delimiters to saveD
		error errStr number errNum
	end try
	set AppleScript's text item delimiters to saveD
	return (txt)
end list_to_text

Se qualcuno perde un po' del suo tempo per risolvere l'inghippo mi fa un gran favore!

D

#2 chebfarid

chebfarid

    Melina di Platino

  • Forum User +
  • 5982 Messaggi:
  • Sesso:Maschietto
  • Località:Milano
  • Interessi:Bridge - Saluki - Programmazione - Letture - Cucina - San Francisco Giants

Inviato 08 gennaio 2012 - 12:32

Vorresti quindi fare il contrario di quello che ha fatto l'autore dello script originale, ho capito bene?
Ovvero, hai dei brani italiani (e francesi, immagino) che per colpa di qualcuno contengono parole che iniziano con lettere maiuscole anche se non dovessero?
O vuoi cambiare anche i brani inglesi (dove le regole della corretta intitolazione seguirebbero la procedura dell'autore dello script) ?

Ciao
Farid

#3 Signor D

Signor D

    Melina d'Oro

  • Staff
  • 3264 Messaggi:
  • Sesso:Maschietto
  • Località:Parigi

Inviato 08 gennaio 2012 - 12:51

Miro i titoli italiani (e francesi, e latini), insomma, quelli che non seguono in effetti lo script.
Quasi il contrario, quindi: lo script dell'autore mette la prima lettera come maiuscola, qui se non ho capito male
else if (word_counter = 1) then
                                                --Capitalize first word in title.
                                                my SetCase(aWord)

Dopo di che lo script, se non ho capito male, confronta le parole del titolo con una lista di eccezioni (--===========LIST OF LOWERCASE WORDS===========--) e quindi, se trova una parola che coincide con quelle della lista, le sostituisce a quelle presenti nel titolo, assicurando così la transizione da maiuscole a minuscole. Sbaglio?

La parte che si occupa di questo mi sembra essere

else
                                                --For words not beginning or ending the title (middle words).
                                                repeat with my_lowercase_Match in lowercase_words
                                                        --Check if any of the middle words belong to the list of lowerase words.
                                                        if (my_lowercase_Match as text) = (aWord as text) then
                                                                set lowercase_match to true
                                                                exit repeat
                                                        end if
                                                end repeat
                                                if lowercase_match then
                                                        --Lowercase matching words in lowercase_words list (actually just copy the word from the list).
                                                        set newWord to my_lowercase_Match as text
                                                        set lowercase_match to false
                                                else
                                                        --Capitalize the rest of the words.
                                                        my SetCase(aWord)

Ed andrebbe sostituita con una che trasformi in minuscole. A naso (sono sempre meno sicuro di me) una cosa del genere my Setlowercase (aWord) da definire poi in coda.
Ho guardato un po', ma non sono riuscito a trovare degli script per mettere le minuscole, tranne uno che non sono riuscito ad integrare e che, sembra, non prende in considerazione spazi e segni di interpunzione, che finiscono per sparire.

D

#4 chebfarid

chebfarid

    Melina di Platino

  • Forum User +
  • 5982 Messaggi:
  • Sesso:Maschietto
  • Località:Milano
  • Interessi:Bridge - Saluki - Programmazione - Letture - Cucina - San Francisco Giants

Inviato 09 gennaio 2012 - 12:00

Visualizza MessaggioSignor D, il 08 gennaio 2012 - 12:51, ha scritto:

lo script dell'autore mette la prima lettera come maiuscola, qui se non ho capito male
else if (word_counter = 1) then
                                                --Capitalize first word in title.
                                                my SetCase(aWord)
Esattamente: SetCase(aWord) è un handler, il nome usato in AppleScript per quello che in altri linguaggi si chiamerebbe una funzione. La variabile aWord all'interno della parentesi è il cosiddetto parametro del handler, ovvero un oggetto (in questo caso una stringa di testo) necessario per lo svolgimento del handler.
Non ho capito ogni dettaglio dello script di Dougie perché molte sono le vie che portano a Roma e ogni scripter ha il suo proprio percorso logico e procedurale per ottenere il risultato desiderato.
Comunque per fare le modifiche che interessano a te bisogna proprio lavorare su SetCase(aWord).

Qui il handler con i miei commenti in corsivo:

Citazione

--The handler taking care of the casing of words.
on SetCase(aWord)
     repeat with j from 1 to (length of aWord) -- fare un loop dal primo all'ultimo carattere di "aWord"
          if other_chars contains (character j of aWord) then -- ovvero, il carattere in elaborazione è uno degli speciali raccolti nella lista "other_chars"
               set j to (character j of aWord) -- allora non cambiare il carattere, lascialo così com'è e
               set newWord to newWord & j -- aggiungilo alla stringa "newWord"
               set other_chars_match to true
          else if other_chars_match then
               set j to (character j of aWord)
               if ((id of j) is greater than 96) and ((id of j) is less than 123) then -- 97-122 sono i codici ASCII delle minuscole "a-z"
                    set newWord to newWord & (character id ((id of j) - 32)) -- mentre 65-90 sono i caratteri ASCII "A-Z", quindi 97 ("a") - 32 = 65 ("A")
               else if ((id of j) is greater than 64) and ((id of j) is less than 91) then -- queste sono le maiuscole che
                    set newWord to newWord & j -- nello script originale non vengono cambiate
               else
                    set newWord to newWord & j
               end if
               set other_chars_match to false
          else if (j = 1) then -- una varinate del codice sopra che si occupa di parole con solo UN carattere
               set j to (character j of aWord)
               if ((id of j) is greater than 96) and ((id of j) is less than 123) then
                    set newWord to newWord & (character id ((id of j) - 32))
               else
                    set newWord to newWord & j
               end if
          else
               set j to (character j of aWord)
               if ((id of j) is greater than 96) and ((id of j) is less than 123) then
                    set newWord to newWord & j
               else if ((id of j) is greater than 64) and ((id of j) is less than 91) then
                    set x to (character id ((id of j) + 32))
                    set newWord to newWord & x
               else
                    set newWord to newWord & j
               end if
          end if
     end repeat
end SetCase
-------------------------
[This script was automatically tagged for color coded syntax by Convert Script to Markup Code]


In sintesi lo script seziona la stringa proveniente da iTunes (artista, titolo ecc...) in singole parole che vengono passate, appunto come parametro al handler SetCase(aWord).
Il handler esamina se la pima lettere è minuscola (ASCII code 97-122) e in caso affermativo lo trasforma in maiuscolo (ASCII code originale meno 32), riassembla la parola, la "ritorna" come risultato allo script principale che poi sostituisce la parola originale in iTunes con quella nuova.

Per fare il contrario bisogna quindi modificare queste parti:
if ((id of j) is greater than 96) and ((id of j) is less than 123) then -- 97-122 sono i codici ASCII delle minuscole "a-z"
set newWord to newWord & (character id ((id of j) - 32)) -- mentre 65-90 sono i caratteri ASCII "A-Z", quindi 97 ("a") - 32 = 65 ("A") 
Se l'ASCII code è fra 65 e 90 (allora si tratta di una maiuscola) bisogna aggiungere invece di sottrarre il valore 32 per arrivare al corrispondente carattere minuscolo.
Tradotto in codice AppleScript:
if ((id of j) > 64) and ((id of j) < 91) then
set newWord to newWord & (character id ((id of j) + 32))
Questa modifica va applicata a tutte le ricorrenze di questa formula nell'handler.
Faccio un test e rimando lo script completo.

Ciao
Farid

Messaggio modificato da chebfarid il 09 gennaio 2012 - 12:35
Errori nei codici ASCII


#5 chebfarid

chebfarid

    Melina di Platino

  • Forum User +
  • 5982 Messaggi:
  • Sesso:Maschietto
  • Località:Milano
  • Interessi:Bridge - Saluki - Programmazione - Letture - Cucina - San Francisco Giants

Inviato 09 gennaio 2012 - 12:33

Ecco il handler SetCase(aWord) nuovo:

Citazione

--The handler taking care of the casing of words.
on SetCase(aWord)
     repeat with j from 1 to (length of aWord) -- fare un loop dal primo all'ultimo carattere di "aWord"
          if other_chars contains (character j of aWord) then -- ovvero, il carattere in elaborazione è uno degli speciali raccolti nella lista "other_chars"
               set j to (character j of aWord) -- allora non cambiare il carattere, lascialo così com'è e
               set newWord to newWord & j -- aggiungilo alla stringa "newWord"
               set other_chars_match to true
          else if other_chars_match then
               set j to (character j of aWord)
               if ((id of j) > 64) and ((id of j) < 91) then -- 65-90 sono i caratteri ASCII "A-Z", mentre
                    set newWord to newWord & (character id ((id of j) + 32)) -- 97-122 sono i codici ASCII delle minuscole "a-z"
               else if ((id of j) is greater than 64) and ((id of j) is less than 91) then -- queste sono le maiuscole che
                    set newWord to newWord & (character id ((id of j) + 32))
               else
                    set newWord to newWord & j
               end if
               set other_chars_match to false
          else if (j = 1) then -- una variante del codice sopra che si occupa di parole con solo UN carattere
               set j to (character j of aWord)
               if ((id of j) > 64) and ((id of j) < 91) then
                    set newWord to newWord & (character id ((id of j) + 32))
               else
                    set newWord to newWord & j
               end if
          else
               -- ==== Nota FM: non ho ancora capito a quale situazione si riferisce questa parte: ====
               set j to (character j of aWord)
               if ((id of j) is greater than 96) and ((id of j) is less than 123) then
                    set newWord to newWord & j
               else if ((id of j) is greater than 64) and ((id of j) is less than 91) then
                    set x to (character id ((id of j) + 32))
                    set newWord to newWord & x
               else
                    set newWord to newWord & j
               end if
               -- ==== fine Nota FM ====
          end if
     end repeat
end SetCase
-------------------------
[This script was automatically tagged for color coded syntax by Convert Script to Markup Code]


Mi sembra che funzioni. Unico neo è che trasforma in minuscola anche il primo carattere di ogni stringa, problema che non si poneva nell'originale inglese.
Bisogna quindi ancora inventarsi un metodo che riconverta il primo carattere di ogni stringa in maiuscolo.
Stay tuned :happy:

Ciao
Farid

#6 Signor D

Signor D

    Melina d'Oro

  • Staff
  • 3264 Messaggi:
  • Sesso:Maschietto
  • Località:Parigi

Inviato 09 gennaio 2012 - 13:00

Probabilmente avrò equivocato, ma mi era parso di capire che lo script originale prevedesse di mettere la prima parola del titolo in maiuscolo, sempre e comunque, e di analizzare solo per le parole seguenti la presenza o meno di maiuscole. Se anche così non fosse, forse il problema si potrebbe risolvere (a suo tempo, con comodo) così, no?

D

#7 chebfarid

chebfarid

    Melina di Platino

  • Forum User +
  • 5982 Messaggi:
  • Sesso:Maschietto
  • Località:Milano
  • Interessi:Bridge - Saluki - Programmazione - Letture - Cucina - San Francisco Giants

Inviato 09 gennaio 2012 - 13:21

Infatti, lo faceva. Ma visto che era lo stesso handler che avevo modificato per ottenere le parole minuscole questo effetto era andato perso. :)
Comunque risolto:
Bisogna aggiungere un secondo handler proprio per la prima parola di ogni stringa, si chiama SetUpperCase(aWord).
Questo nuovo handler va chiamato a questo punto dello script:
else if (word_counter = 1) then
	--Capitalize first word in title.
	my SetUpperCase(aWord)

Con più familiarità con le intenzioni e la logica dell'autore di sicuro si potrebbe risolvere in modo più elegante, ma comunque ora funziona.
Ecco lo script completo:

Citazione

--===========LIST OF TAGS TO MODIFY===========--
--These are the tags that will be selected by default.
property my_tags_to_modify : {"name", "album"}

--This is the complete list of tags -->which you shouldn't modify unless you know what you are doing 8>)
property tags_to_modify : {"name", "album", "artist", "composer", "grouping", "show"}

--===========LIST OF LOWERCASE WORDS===========--
--These are the words that will remain lowercase, unless they begin or end the title.
property lowercase_words : {"a", "an", "and", "at", "but", "by", "for", "in", "nor", "of", "on", "or", "so", "the", "to", "with"}
--Feel free to add these: "amid", "anti", "as", "down", "into", "like", "near", "off", "onto", "out", "over", "past", "per", "plus", "save", "some", "than", "till", "up", "upon", "via", "yet"

--===========LIST OF UNMODIFIED WORDS===========--
--These are the words that won't be modified at all. It's a good place to put all-uppercase words.
property unmodified_words : {"FM", "USA", "WDPK", "OYF’N", "UR", "TV", "MGM", "DVD", "ABC", "CD", "USSR", "CA", "WA", "NY", "NYC", "LP", "EP", "VHS", "UK", "GB", "'Bout", "'Cause", "o'", "'n'", "n'", "McCartney", "vs.", "de", "feat.", "Pi-hsien", "von", "van"}

--===========LIST OF TRAILING CHARACTERS===========--
--Any word trailed by a character in this list will be title cased. (ie. "a song" (with a remix) -> "A Song" (With a Remix))
property other_chars : "_!\"$%&/()=¿?@¡|#¢[infin]“”[]{}*-+•«»—´`ºª…:;."



--===========NO NEWBIE-USER-MODIFIABLE PARTS BELOW===========--

property lowercase_match : false
property unmodified_Match : false
property other_chars_match : false
property my_tags : my_tags_to_modify
property myTitle : "Proper English Title Capitalization"

global aWord, newWord

tell application "iTunes"
     set mySelectedTracks to selection
     if mySelectedTracks is not {} then
          set old_fi to fixed indexing
          set fixed indexing to true
          set songs_selected to (count mySelectedTracks)
          
          if songs_selected = 1 then
               set songs_selected_message to "Brani selezionati: " & songs_selected & "." as text
          else
               set songs_selected_message to "Brani selezionati: " & songs_selected & "." as text
          end if
          
          set choice to button returned of (display dialog songs_selected_message & return & return & "Che facciamo?" buttons {"Lascia stare", "Configura…", "Modifica"} default button 3 with icon 1 with title myTitle)
          
          if choice = "Configura…" then
               set my_tags_to_modify to (choose from list tags_to_modify with prompt "Scegli gli attributi che vuoi modificare (quelli non selezionati verranno ignorati tags will be ignored):" default items my_tags_to_modify with title myTitle with multiple selections allowed without empty selection allowed)
               if my_tags_to_modify is false then
                    set my_tags_to_modify to my_tags
                    run me
               else
                    display dialog "Possiamo andare." buttons {"Lascia stare", "Modifica"} default button 2 with title myTitle
               end if
          end if
          
          repeat with selected_tag in my_tags_to_modify --Check which tags are to be modified.
               repeat with aTrack in mySelectedTracks
                    set selected_tag to selected_tag as text
                    
                    if selected_tag = "name" then set theTitle_as_List to (my text_to_list(aTrack's name, space))
                    if selected_tag = "artist" then set theTitle_as_List to (my text_to_list(aTrack's artist, space))
                    if selected_tag = "composer" then set theTitle_as_List to (my text_to_list(aTrack's composer, space))
                    if selected_tag = "album" then set theTitle_as_List to (my text_to_list(aTrack's album, space))
                    if selected_tag = "show" then set theTitle_as_List to (my text_to_list(aTrack's show, space))
                    if selected_tag = "grouping" then set theTitle_as_List to (my text_to_list(aTrack's grouping, space))
                    
                    set newTitle to {}
                    set last_item to (count theTitle_as_List)
                    set word_counter to 1
                    
                    repeat with aWord in theTitle_as_List
                         set newWord to ""
                         repeat with my_unmodified_Match in unmodified_words
                              --Check if any of the words belong to the list of unmodified words.
                              if (my_unmodified_Match as text) = (aWord as text) then
                                   set unmodified_Match to true
                                   exit repeat
                              end if
                         end repeat
                         if unmodified_Match then
                              --Unmodify matching words in unmodified_words list (actually just copy the word from the list).
                              set newWord to my_unmodified_Match as text
                              set unmodified_Match to false
                         else if (word_counter = 1) then
                              -- ===== LA PRIMA PAROLA INIZIA CON UNA MAIUSCOLA: =========
                              my SetUpperCase(aWord)
                         else
                              --For words not beginning or ending the title (middle words).
                              repeat with my_lowercase_Match in lowercase_words
                                   --Check if any of the middle words belong to the list of lowerase words.
                                   if (my_lowercase_Match as text) = (aWord as text) then
                                        set lowercase_match to true
                                        exit repeat
                                   end if
                              end repeat
                              if lowercase_match then
                                   --Lowercase matching words in lowercase_words list (actually just copy the word from the list).
                                   set newWord to my_lowercase_Match as text
                                   set lowercase_match to false
                              else
                                   --Capitalize the rest of the words.
                                   my SetCase(aWord)
                              end if
                         end if
                         copy newWord to end of newTitle
                         set word_counter to (word_counter + 1)
                    end repeat
                    
                    -->> log (my list_to_text(newTitle, space)) -- de-bugging only
                    
                    try
                         if selected_tag = "name" then set aTrack's name to my list_to_text(newTitle, space)
                         if selected_tag = "artist" then set aTrack's artist to my list_to_text(newTitle, space)
                         if selected_tag = "composer" then set aTrack's composer to my list_to_text(newTitle, space)
                         if selected_tag = "album" then set aTrack's album to my list_to_text(newTitle, space)
                         if selected_tag = "show" then set aTrack's show to my list_to_text(newTitle, space)
                         if selected_tag = "grouping" then set aTrack's grouping to my list_to_text(newTitle, space)
                    end try
                    
               end repeat
          end repeat
          
          copy old_fi to fixed indexing
          display dialog return & return & "Tutto fatto!" buttons {"Bene"} default button 1 with icon 1 with title myTitle giving up after 5
     else
          display dialog "Non hai selezionato alcun brano." buttons {"Lascia stare"} default button 1 with icon 0
     end if
end tell

--The handler taking care of the casing of words.
on SetCase(aWord)
     repeat with j from 1 to (length of aWord) -- fare un loop dal primo all'ultimo carattere di "aWord"
          if other_chars contains (character j of aWord) then -- ovvero, il carattere in elaborazione è uno degli speciali raccolti nella lista "other_chars"
               set j to (character j of aWord) -- allora non cambiare il carattere, lascialo così com'è e
               set newWord to newWord & j -- aggiungilo alla stringa "newWord"
               set other_chars_match to true
          else if other_chars_match then
               set j to (character j of aWord)
               if ((id of j) > 64) and ((id of j) < 91) then -- 65-90 sono i caratteri ASCII "A-Z", mentre
                    set newWord to newWord & (character id ((id of j) + 32)) -- 97-122 sono i codici ASCII delle minuscole "a-z"
               else if ((id of j) is greater than 64) and ((id of j) is less than 91) then -- queste sono le maiuscole che
                    set newWord to newWord & (character id ((id of j) + 32))
               else
                    set newWord to newWord & j
               end if
               set other_chars_match to false
          else if (j = 1) then -- una variante del codice sopra che si occupa di parole con solo UN carattere
               set j to (character j of aWord)
               if ((id of j) > 64) and ((id of j) < 91) then
                    set newWord to newWord & (character id ((id of j) + 32))
               else
                    set newWord to newWord & j
               end if
          else
               -- ==== Nota FM: non ho ancora capito a quale situazione si riferisce questa parte: ====
               set j to (character j of aWord)
               if ((id of j) is greater than 96) and ((id of j) is less than 123) then
                    set newWord to newWord & j
               else if ((id of j) is greater than 64) and ((id of j) is less than 91) then
                    set x to (character id ((id of j) + 32))
                    set newWord to newWord & x
               else
                    set newWord to newWord & j
               end if
               -- ==== fine Nota FM ====
          end if
     end repeat
end SetCase

-- ===== NUOVO ======
on SetUpperCase(aWord)
     repeat with j from 1 to (length of aWord)
          if other_chars contains (character j of aWord) then
               set j to (character j of aWord)
               set newWord to newWord & j
               set other_chars_match to true
          else if other_chars_match then
               set j to (character j of aWord)
               if ((id of j) > 64) and ((id of j) < 91) then -- maiuscolo = OK
                    set newWord to newWord & j
               else if ((id of j) > 96) and ((id of j) < 123) then -- minuscolo va convertito
                    set newWord to newWord & (character id ((id of j) - 32))
                    (* else
                    set newWord to newWord & j *)

               end if
               set other_chars_match to false
          else if (j = 1) then -- una variante del codice sopra che si occupa di parole con solo UN carattere
               set j to (character j of aWord)
               if ((id of j) > 96) and ((id of j) < 123) then
                    set newWord to newWord & (character id ((id of j) - 32))
               else
                    set newWord to newWord & j
               end if
          else
               -- ==== Nota FM: non ho ancora capito a quale situazione si riferisce questa parte: ====
               set j to (character j of aWord)
               if ((id of j) is greater than 96) and ((id of j) is less than 123) then
                    set newWord to newWord & j
               else if ((id of j) is greater than 64) and ((id of j) is less than 91) then
                    set x to (character id ((id of j) + 32))
                    set newWord to newWord & x
               else
                    set newWord to newWord & j
               end if
               -- ==== fine Nota FM ====
          end if
     end repeat
end SetUpperCase

on text_to_list(txt, delim)
     set saveD to AppleScript's text item delimiters
     try
          set AppleScript's text item delimiters to {delim}
          set theList to every text item of txt
     on error errStr number errNum
          set AppleScript's text item delimiters to saveD
          error errStr number errNum
     end try
     set AppleScript's text item delimiters to saveD
     return (theList)
end text_to_list

on list_to_text(theList, delim)
     set saveD to AppleScript's text item delimiters
     try
          set AppleScript's text item delimiters to {delim}
          set txt to theList as text
     on error errStr number errNum
          set AppleScript's text item delimiters to saveD
          error errStr number errNum
     end try
     set AppleScript's text item delimiters to saveD
     return (txt)
end list_to_text
-------------------------
[This script was automatically tagged for color coded syntax by Convert Script to Markup Code]


Have fun :)
Farid

#8 Vladimiro Paglianti

Vladimiro Paglianti

    Primi Passi

  • Forum User +
  • 86 Messaggi:

Inviato 09 gennaio 2012 - 13:36

Interessante. Sto cercando di vedere se c'è un metodo più semplice per implementare la cosa.
Ricapitolando (correggetemi se sbaglio), a partire da una selezione di tracce di itunes, vuoi modificare tutti i titoli in modo che siano tutti in minuscolo, con la prima lettera maiuscola, giusto?

#9 Signor D

Signor D

    Melina d'Oro

  • Staff
  • 3264 Messaggi:
  • Sesso:Maschietto
  • Località:Parigi

Inviato 09 gennaio 2012 - 13:41

Esatto, mantenendo una lista di eccezioni, che può essere alimentata man mano (cui aggiungere, per esempio, Surriento, così Torna a Surriento potrà essere identificato e non corretto).

D

#10 Vladimiro Paglianti

Vladimiro Paglianti

    Primi Passi

  • Forum User +
  • 86 Messaggi:

Inviato 09 gennaio 2012 - 14:07

Ok.
Procediamo a piccoli passi allora.
Innanzi tutto, l'editor ed il linguaggio di scripting. Non AppleScript ma JSTalk.
Puoi scaricare l'editor da qui: JSTalk Editor
se non hai account di itunes, vai sul sito dello sviluppatore e scarica l'applicazione compilata. Tra l'altro, il progetto è opensource.
Il funzionamento è del tutto simile a quello dello Script Editor per applescript.

JSTalk, come il nome fa intuire, è un blend tra JavaScript e SmallTalk.
Permette di mescolare (grazie ad un preprocessore del codice) javascript e Objective-C.

Partiamo con uno script che cambia il nome a tutte le tracce che hai selezionate in itunes, rendendole tutte minuscole, con la prima lettera maiuscola.

var itunes = SBApplication.application_("iTunes")

// get the selected tracks
var tracks = [[itunes selection] get]

// iterate over the tracks' collection
var i = 0
,   track
while( track = tracks[ i++ ])
{
    // get the name of the track and make it lowercase
    var name = [track name].toLowerCase()
    // test if the first char is a letter…
    if ( name[0].toUpperCase != name[0] )
        // … make it uppercase
        name = String.fromCharCode(name.charCodeAt(0)-0x20) + name.substr(1)
    // set the name of the track
    [track setName:name]
}

Come potete vedere, lo script così diventa un po' più "sano"...

Per aggiungere la gestione delle eccezioni, vanno fatte diverse modifiche. A breve...

Messaggio modificato da Vladimiro Paglianti il 09 gennaio 2012 - 14:08


#11 Signor D

Signor D

    Melina d'Oro

  • Staff
  • 3264 Messaggi:
  • Sesso:Maschietto
  • Località:Parigi

Inviato 09 gennaio 2012 - 14:17

Per non scaricare il programma dal Mac App Store (che io cerco di non sostenere): il programma, il sito dell'editore.

D

#12 chebfarid

chebfarid

    Melina di Platino

  • Forum User +
  • 5982 Messaggi:
  • Sesso:Maschietto
  • Località:Milano
  • Interessi:Bridge - Saluki - Programmazione - Letture - Cucina - San Francisco Giants

Inviato 09 gennaio 2012 - 14:46

Visualizza MessaggioVladimiro Paglianti, il 09 gennaio 2012 - 14:07, ha scritto:

Innanzi tutto, l'editor ed il linguaggio di scripting. Non AppleScript ma JSTalk.
Molto interessante, grazie! :)
Non so se trovo il tempo per studiare i segreti di JSTalk, ma comunque, c'è anche una documentazione da qualche parte? Non credo basti conoscere JavaScript, o sbaglio?

Good scripting
Farid

#13 Vladimiro Paglianti

Vladimiro Paglianti

    Primi Passi

  • Forum User +
  • 86 Messaggi:

Inviato 09 gennaio 2012 - 14:59

Visualizza Messaggiochebfarid, il 09 gennaio 2012 - 14:46, ha scritto:

Non so se trovo il tempo per studiare i segreti di JSTalk, ma comunque, c'è anche una documentazione da qualche parte? Non credo basti conoscere JavaScript, o sbaglio?
Esattamente, javascript non basta. occorre anche conoscere un po' di objective-c (perlomeno la sintassi di message-passing ala smalltalk).
La documentazione non è il suo piatto forte purtroppo. per alcune cose la corrispondenza da applescript è 1:1. per altre no.
Io l'ho scoperto una mezz'ora prima di scrivere il post, e capirci qualche cosa è stata dura.
Un documento che mi ha messo sulla buona strada è questo

#14 Vladimiro Paglianti

Vladimiro Paglianti

    Primi Passi

  • Forum User +
  • 86 Messaggi:

Inviato 09 gennaio 2012 - 15:36

Seconda versione dello script, con implementata la lista di parole "speciali".

// [!] get a reference to the application
var itunes = SBApplication.application_("iTunes")

// a list of "special" words
var uc_words = [ 'SomaFM', 'Cliqhop' ]
// the same list, lowercased, to help matching the words.
var uc_words_lower = uc_words.map(function(w){ return w.toLowerCase() })

// [!] get the selected tracks
var tracks = [[itunes selection] get]

// iterate over the tracks' collection
var i = 0
,   track
while( track = tracks[ i++ ])
{
    // get the name of the track
    var name = [track name]

    // do the replacements, using a regular expression
    // the function is invoked for every word of the name.
    name = name.replace( /\S+/g, function( word, position )
    {
        // if the word is found on the list, use the specified case
        // else, if the word is the first of the sentence, make its first letter uppercase
        // otherwise, make it lowercase
        var idx = uc_words_lower.indexOf( word.toLowerCase())
        return ~idx 
        ? uc_words[idx]
        : !position ? word[0].toUpperCase() + word.substr(1) : word.toLowerCase()
    })

    // [!] set the name of the track
    [track setName:name]
}

@chebfarid: le uniche righe di codice che non sono puramente javascript sono contrassegnate da un [!] nel commento che le precede.




1 utente(i) stanno leggendo questa discussione

0 utenti, 1 ospiti, 0 utenti anonimi