如何让AppleScript识别剪贴板中的逗号分隔列表并逐个输出?
解决AppleScript读取剪贴板逗号分隔文本为列表的问题
你的核心问题是没有将剪贴板中的逗号分隔字符串拆分成真正的AppleScript列表,原代码里set theList to {Storage}只是把整个剪贴板内容包装成了只有一个元素的列表,自然只会输出一次。
下面是修改后的代码,能自动把剪贴板里的带引号逗号分隔文本转换成列表并逐个输出:
tell application "Safari" activate set clipboardContent to get clipboard -- 处理剪贴板文本:去除首尾引号(如果存在),按逗号分割 set cleanedText to clipboardContent if cleanedText starts with "\"" then set cleanedText to text 2 thru -2 of cleanedText set AppleScript's text item delimiters to "\"," set rawItems to text items of cleanedText set AppleScript's text item delimiters to "" -- 清理每个条目:去除开头引号和多余空格 set theList to {} repeat with itemText in rawItems set trimmedItem to trimWhitespace(text 2 thru end of itemText) set end of theList to trimmedItem end repeat tell application "System Events" repeat with varName in theList keystroke varName delay 0.2 keystroke return delay 0.2 end repeat end tell end tell -- 辅助函数:去除字符串首尾空格 on trimWhitespace(inputText) set leadingTrimmed to text ((first character of inputText is space) as integer) + 1 thru end of inputText set trailingTrimmed to text 1 thru ((length of leadingTrimmed) - (last character of leadingTrimmed is space) as integer) of leadingTrimmed return trailingTrimmed end trimWhitespace
关键修改说明:
- 先清理剪贴板文本:如果文本首尾有引号,先去掉;然后用
",作为分隔符拆分文本,得到原始条目列表。 - 遍历原始条目,每个条目去掉开头的引号和前后空格,得到干净的内容。
- 替换了复杂的
repeat until循环,用更简洁的repeat with直接遍历列表,逻辑更清晰。
如果你的剪贴板内容格式固定(比如每个条目都用","分隔且带引号),这段代码就能完美自动处理,无需手动修改脚本内容。
内容的提问来源于stack exchange,提问作者Rassy Raoof
相关产品推荐
相关产品推荐

