首页 > 解决方案 > AppleScript,无法替换文本中的字符

问题描述

我正在开发一个 AppleScript,它以文件名作为参数调用 Python 脚本,例如:

set descriptionFiles to (every file of current_folder whose name extension is "txt")
repeat with textFile in descriptionFiles
   -- run a Python script that clears the xml tags and reformat the text of the file 
    do shell script "python3 '/Users/MBP/Documents/Python/cleanDescription.py' '" & textFile & "'"
end repeat

现在,只要我没有遇到名称中带有单引号的文件,AppleScript 就可以正常工作,此时它会停止并引发错误。

为了纠正这个问题,我一直在尝试在将文件名中的单引号传递给 Python 脚本之前对其进行转义,但这就是我遇到的问题。我正在使用这个例程:

on searchReplace(thisText, searchTerm, replacement)
    set AppleScript's text item delimiters to searchTerm
    set thisText to thisText's text items
    set AppleScript's text item delimiters to replacement
    set thisText to "" & thisText
    set AppleScript's text item delimiters to ""
    return thisText
end searchReplace

用这样的电话:

tell application "Finder"
    set search_T to "'"
    set rep to "\\'"
    set selected to selection as alias
    set textName to selected as text
    set res to searchReplace(textName, search_T, rep)
end tell

在单个文件上使用上面的代码会在 searchReplace(textName, search_T, rep) 部分引发错误,编号为 -1708

有任何想法吗 ?

标签: stringreplaceapplescript

解决方案


在 AppleScript 中转义特殊字符最可靠的方法是quoted form of. 它可以顺利处理所有形式的报价。永远不要自己做。即使quote路径不包含空格,始终成行也是一个好习惯。do shell script

另一个问题是textFile应该是 POSIX 路径而不是 Finder 说明符。并获得一次python脚本的路径

set pythonScriptPath to POSIX path of (path to documents folder) & "Python/cleanDescription.py"
set descriptionFiles to (every file of current_folder whose name extension is "txt")
repeat with textFile in descriptionFiles
    -- run a Python script that clears the xml tags and reformat the text of the file 
    do shell script "python3" & space & quoted form of pythonScriptPath & space & quoted form of POSIX path of (textFile as text)
end repeat

推荐阅读