Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在AppleScript中实现字符串插值的简单方法_Applescript - Fatal编程技术网

在AppleScript中实现字符串插值的简单方法

在AppleScript中实现字符串插值的简单方法,applescript,Applescript,我想在AppleScript中实现一个字符串插值,类似于基本的python实现。例如,在python中: print('Hello {}'.format('earth')) #> Hello World 在AppleScript中,如何实现格式处理程序 to format(theString, {tokens}) -- TODO end format log format("Hello {}", {"Apple"}) -- # Hell

我想在AppleScript中实现一个字符串插值,类似于基本的python实现。例如,在python中:

print('Hello {}'.format('earth')) #> Hello World
在AppleScript中,如何实现
格式
处理程序

to format(theString, {tokens})
    -- TODO
end format

log format("Hello {}", {"Apple"})  -- # Hello Apple

python语法和AppleScript/ObjC语法不兼容

如果您只讨论一个参数,那么可以借助
NSString
stringWithFormat

use AppleScript version "2.5"
use framework "Foundation"
use scripting additions

to format(theString, tokens)
    return (current application's NSString's stringWithFormat_(theString, tokens)) as text
end format

log format("Hello %@", "Apple") -- # Hello Apple
对于更多参数,您必须使用
if-else
子句将参数数组转换为ObjC
va_列表

to format(theString, tokens)
    set numberOfArguments to count tokens
    if numberOfArguments = 1 then
        return (current application's NSString's stringWithFormat_(theString, item 1 of tokens)) as text
    else if numberOfArguments = 2 then
        return (current application's NSString's stringWithFormat_(theString, item 1 of tokens, item 2 of tokens)) as text
    else if numberOfArguments = 3 then
        return (current application's NSString's stringWithFormat_(theString, item 1 of tokens, item 2 of tokens, item 3 of tokens)) as text
    else
        error "Invalid number of arguments"
    end if
end format

log format("Hello I'm %@ and I'm %@ years old", {"John", 25}) -- # Hello I'm John and I'm 25 years old

我使用sed编写了一个简单的实现

to format(theString as text, theTokens as list)
    if class of theTokens is text then set theTokens to {theTokens}
    set builtString to theString
    repeat with nextToken in theTokens 
        set builtString to do shell script "echo '" & builtString & "' | sed 's/{}/" & nextToken & "/'"
    end repeat
    return builtString  
end format
我只在两个场景中进行了测试,我确信还有更多的场景没有涉及:

format("Hello {}", "baby") -- # Hello baby
"Hello {}, how are you {}", {"baby", "mom"}  -- # Hellow baby, how are you mom

感谢您的示例代码。TBH,我还没有准备好尝试ObjC,至少还没有,我会尝试一下,看看是否可以从那里构建。我最初的想法是查找和替换字符串中出现的{},类似于我实现查找和替换时的想法。只是担心它不会是一个简单的实现。我得到了
error“NSString不理解“stringWithFormat_u”消息。”
我需要安装/配置任何东西才能使其工作吗?在处理AppleScriptObjC时,必须始终将三行(至少前两行)
use
放在脚本中。解析
{}
在AppleScript中不是一件小事。噢,很酷,谢谢你,我真傻。