string - 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
有任何想法吗 ?
解决方案
在 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
推荐阅读
- jquery - 如何在 asp.net core 中使用 ajax 减少产品数量
- angular - 从 9 升级到 11 后,angular primeng 选项列表样式损坏
- jenkins - 使用特定目录时,Jenkins 将文件复制到远程服务器失败
- python - 有没有办法根据前一行中不同列的值替换数据框中的行的值?
- python - 如何在 selenium python 中经过一定时间后停止加载页面?
- python - 关于通过 Python 进行(超)参数优化的一般问题
- python - np.sum/np.count_nonzero() 达到某个最大数量
- python - Openpyxl 正在删除目标电子表格中的对象
- esp8266 - 使用 ESP8266 和 arduino uno 向 TELNET 应用程序发送数据
- javascript - 按升序和降序从数组中选择随机值