可以使用其子句来过滤文本元素列表,例如单词,字符和段落

时间:2013-09-13 21:19:30

标签: applescript

我有以下工作示例AppleScript片段:

set str to "This is a string"

set outlist to {}
repeat with wrd in words of str
    if wrd contains "is" then set end of outlist to wrd
end repeat

我知道AppleScript中的子句通常可用于替换重复循环,以实现显着的性能提升。但是,对于文字元素列表,如单词,字符和段落,我无法找到一种方法来使这项工作。

我试过了:

set outlist to words of str whose text contains "is"

这失败了:

error "Can’t get {\"This\", \"is\", \"a\", \"string\"} whose text contains \"is\"." number -1728

,大概是因为“text”不是文本类的属性。查看AppleScript Reference for the text class,我看到“引用的表单”是文本类的属性,所以我一半期望这个工作:

set outlist to words of str whose quoted form contains "is"

但这也失败了:

error "Can’t get {\"This\", \"is\", \"a\", \"string\"} whose quoted form contains \"is\"." number -1728

有没有办法用AppleScript中的where子句替换这样的重复循环?

2 个答案:

答案 0 :(得分:1)

来自AppleScript 1-2-3

的第534页(使用文字)
  

AppleScript不考虑段落,单词和字符   可编写脚本的对象,可以使用它们的值来定位   使用过滤器引用或其搜索的搜索中的属性或元素   子句。

这是另一种方法:

set str to "This is a string"
set outlist to paragraphs of (do shell script "grep -o '\\w*is\\w*' <<< " & quoted form of str)

答案 1 :(得分:1)

正如@adayzdone所示。看起来你运气不好。

但你可以尝试使用这样的偏移命令。

    set wrd to "I am here"
        set outlist to {}

        set str to " This is a word"

  if ((offset of space & "is" & space in str) as integer) is greater than 0 then set end of outlist to wrd

请注意“是”周围的空格。这可以确保Offset找到一个完整的单词。偏移将在“This”中找到第一个匹配的“is”。

更新。

将其用作OP想要的

set wrd to "I am here"
set outlist to {}

set str to " This is a word"
repeat with wrd in words of str

    if ((offset of "is" in wrd) as integer) is greater than 0 then set end of outlist to (wrd as string)
end repeat

- &gt; {“This”,“is”}