为什么这一小段代码不起作用?

时间:2012-09-05 15:19:29

标签: text applescript

一个简单的问题:以下AppleScript代码有什么问题?它应该做的是在字符串中获取文本项的位置(由用户提供的分隔符分隔)。但到目前为止,它不起作用。 Script Debugger简单地说,“无法继续return_string_position”而没有任何特定错误。关于什么是错的任何想法?

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

2 个答案:

答案 0 :(得分:0)

tell system events命令不正确,应排除。此外,您不需要使用“”的文本项分隔符来制作单词列表,只需使用“每个单词”。最后,您的代码将仅返回传递参数的最后一个匹配,这将返回EACH匹配。

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.")

答案 1 :(得分:0)

你的问题是系统事件认为函数return_string_position是它自己的一个(如果你看看字典,你会发现它不是)。这很容易解决;只需在调用my之前添加return_string_position即可。

您的新代码:

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
...

或者您可以使用adayzdone的解决方案。在这种情况下,他/她的解决方案非常适合这项工作,因为在处理简单的文本事物时,确实没有必要针对系统事件。