首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么这一小段代码不能工作呢?

为什么这一小段代码不能工作呢?
EN

Stack Overflow用户
提问于 2012-09-05 23:19:29
回答 2查看 64关注 0票数 0

我有一个简短的问题:下面的AppleScript代码有什么问题?它应该做的是获取文本项在字符串中的位置(由用户提供的分隔符分隔)。但到目前为止,它并不起作用。Script Debugger简单地说,"Can't continue return_string_position“没有任何特定的错误。有什么不对劲的想法吗?

代码语言:javascript
运行
复制
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
EN

回答 2

Stack Overflow用户

发布于 2012-09-05 23:53:11

“告知系统事件”命令不正确,应将其排除。此外,您不需要使用文本项分隔符“”来创建单词列表,只需使用"every word of“即可。最后,您的代码将只返回传递参数的最后一个匹配项,这将返回每个匹配项。

代码语言:javascript
运行
复制
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.")
票数 0
EN

Stack Overflow用户

发布于 2012-09-06 00:22:15

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

你的新代码:

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12284673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档