如何在 Applescript/mac 上分析字符串

如何在 Applescript/mac 上分析字符串

我该如何编写脚本来分析 Applescript(或 Mac 的其他脚本程序)中的字符串?例如:扫描文本文件中的“我喜欢吃”,复制后续文本,以“。”结尾,这样如果我的文件是“我喜欢吃苹果。我喜欢吃樱桃。我喜欢吃葡萄、山核桃和桃子。”,它将返回“苹果樱桃葡萄、山核桃和桃子”

答案1

在 AppleScript 中处理文本的常用方法是使用内置的全局属性text item delimiters。您可以使用它将单个字符串拆分成多个部分(使用text items … of引用形式时)、选择范围端点(以text item N引用text … of形式使用时)以及将多个部分合并为一个字符串(将列表强制转换为字符串时)。

to pickText(str, startAfter, stopBefore)
    set pickedText to {}
    set minLength to (length of startAfter) + (length of stopBefore)
    repeat while length of str is greater than or equal to minLength
        -- look for the start marker
        set text item delimiters to startAfter
        -- finish if it is not there
        if (count of text items of str) is less than 2 then exit repeat
        -- drop everything through the end of the first start marker
        set str to text from text item 2 to end of str

        -- look for the end marker
        set text item delimiters to stopBefore
        -- finish if it is not there
        if (count of text items of str) is less than 2 then exit repeat
        -- save the text up to the end marker
        set end of pickedText to text item 1 of str

        -- try again with what is left after the first end marker
        set str to text from text item 2 to end of str
    end repeat
    set text item delimiters to " "
    pickedText as string
end pickText

-- process some “hard coded” text
set s to "I love eating apples. I love eating cherries. I love eating grapes, pecans, and peaches."
pickText(s, "I love eating ", ".") --> "apples cherries grapes, pecans, and peaches"


-- process text from a file
set s to read file ((path to desktop folder as string) & "Untitled.txt")
pickText(s, "I love eating ", ".")

相关内容