问题
Just a quick question: What's wrong with the following AppleScript code? What it's supposed to do is get the position of a text item (separated by a user-provided delimiter) within a string. But thus far, it doesn't work. Script Debugger simply says, "Can't continue return_string_position" without any specific errors. Any ideas as to what's wrong?
tell application "System Events"
set the_text to "The quick brown fox jumps over the lazy dog"
set word_index to return_string_position("jumps", the_text, " ")
end tell
on return_string_position(this_item, this_str, delims)
set old_delims to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set this_list to this_str as list
repeat with i from 1 to the count of this_list
if item i of this_list is equal to this_item then return i
end repeat
set AppleScript's text item delimiters to old_delims
end return_string_position
回答1:
Your issue is that System Events thinks the function return_string_position
is one of its own (if you'll look at the dictionary, you'll find that it isn't). This is very easily resolved; just add my
before the call to return_string_position
.
Your new code:
tell application "System Events"
set the_text to "The quick brown fox jumps over the lazy dog"
set word_index to my return_string_position("jumps", the_text, " ")
end tell
...
Or you can use adayzdone's solution. In this case, his/her solution is perfect for the job because there really isn't any need to target system events when working with simple textual things.
回答2:
The tell system events command is incorrect and should be excluded. Also, you don't need to use text item delimiters of " " to make a list of words, simply use "every word of". Lastly, your code will only return the last match of the passed parameter, this will return EACH match.
on return_string_position(this_item, this_str)
set theWords to every word of this_str
set matchedWords to {}
repeat with i from 1 to count of theWords
set aWord to item i of theWords
if item i of theWords = this_item then set end of matchedWords to i
end repeat
return matchedWords
end return_string_position
return_string_position("very", "The coffee was very very very very very ... very hot.")
来源:https://stackoverflow.com/questions/12284673/why-wont-this-short-bit-of-code-work