如何永久更新AppleScript列表?代码持久化需求咨询
永久保存AppleScript中的词汇列表解决方案
要让你新增的词汇在每次脚本运行时都能被识别,核心是把列表数据持久化存储到本地文件,而不是只保留在脚本运行的内存中。下面是修改后的完整代码和详细说明:
修改思路
- 用本地plist文件存储词汇列表(plist是Apple生态常用的配置文件格式,AppleScript读写起来很方便)
- 脚本启动时优先读取文件中的列表,文件不存在则使用初始默认列表
- 新增词汇后,立即将更新后的列表写回文件,确保下次运行能加载最新数据
完整代码
-- 定义存储词汇列表的plist文件路径,放在用户偏好设置文件夹下 set vocabFilePath to (path to preferences folder as text) & "HappyVocabulary.plist" -- 读取已保存的词汇列表,文件不存在则使用初始默认列表 try set TheStringsQ1Happy to read plist file vocabFilePath on error set TheStringsQ1Happy to {"Fabulous", "Great", "Alright", "Excited", "Not Bad", "", "Decent", "Fine", "Awesome", "Bored", "Cool", "Sad", "Fantastic", "Alright", "Good", "Ok"} end try -- 处理用户输入 set theResponse to the text returned of (display dialog "" default answer "" giving up after 5) if TheStringsQ1Happy contains theResponse then display dialog "That's Great!" else say "That term is not in my vocabulary. Would you like me to add it?" using "Tom" speaking rate 220 set theResponseNotInVocabulary to text returned of (display dialog "" default answer "" giving up after 5) if theResponseNotInVocabulary is "Yes" then set end of TheStringsQ1Happy to theResponse -- 将更新后的列表写入文件,永久保存 write TheStringsQ1Happy to plist file vocabFilePath display dialog "Added successfully!" end if end if
关键说明
- 存储路径:我把plist文件放在了
~/Library/Preferences文件夹下,这是macOS存储用户配置的标准位置,不会轻易被误删 - 读写逻辑:用
try...on error块处理文件不存在的情况,第一次运行时会自动创建初始列表的文件 - 永久保存:每次新增词汇后,通过
write...to plist file命令把更新后的列表写入文件,确保修改被持久化
如果之后想要重置词汇列表,只需要找到~/Library/Preferences/HappyVocabulary.plist文件删除即可,下次运行脚本会重新生成初始列表。
内容的提问来源于stack exchange,提问作者Manan Shukla
相关产品推荐
相关产品推荐

