Applescript and SpeechRecognitionServer: reading in a file as “listen for”

applescript

In place of the list in

tell app "SpeechRecognitionServer to set theQueryList to listen for {"list item 1", "list item 2"...}

I'd like to read in a text file that contains the list. Something like

set theQueryList to read POSIX file "/Users/username/folder/text.txt"

The file text.txt contains a list, written out as

"list item 1", "list item 2", ... "list item n"

without brackets and in utf8 (I hope) format. (I created the file by cat'ing it in Terminal.)

This works, somewhat. I mean: I can display the list from text.txt in a dialog, and I can use it in a repeat loop. But it doesn't trigger SpeechRecognitionServer when spoken. (I don't know a better way to say this.) I should mention that when I paste the list from this file into the script, it works fine. So the list items don't seem to be at fault — nor how I say them.

Apologies if I'm a bit fuzzy in my wording here. Grateful for your ideas. Thanks.

Best Answer

The items to listen for need to be in a list, so you will need to extract the items from the text.

If the items in the text are separated by end-of-ine characters:

list item 1
list item 2
list item 3
list item n

you can just get the paragraphs:

set theQueryList to paragraphs of (read POSIX file "/Users/username/folder/text.txt")

If the items in the text are separated by commas (or tabs, or whatever):

list item 1,list item 2,list item 3,list item n

you can use AppleScript's text item delimiters:

set separator to "," -- the separating text
set fileText to (read POSIX file "/Users/username/folder/text.txt")
set {tempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, separator}
set theQueryList to text items of fileText
set AppleScript's text item delimiters to tempTID -- restore original