0

只是一个简单的问题:以下 AppleScript 代码有什么问题?它应该做的是获取字符串中文本项(由用户提供的分隔符分隔)的位置。但到目前为止,它不起作用。脚本调试器简单地说,“无法继续 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
4

2 回答 2

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 的解决方案。在这种情况下,他/她的解决方案非常适合这项工作,因为在处理简单的文本内容时确实不需要针对系统事件。

于 2012-09-05T16:22:14.570 回答
0

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

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.")
于 2012-09-05T15:53:10.973 回答