You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AppleScript循环替换未达预期结果求助(InDesign场景)

解决InDesign脚本批量替换上标字母为数字的问题

你的脚本核心问题在于两点:

  • myLetters列表所有元素都是"a",第一次执行change text就把全部带sup样式的"a"替换成了"1",后续循环再搜索"a"时已经没有匹配项了。
  • 默认的change text是批量替换所有匹配内容,而你需要的是对每一个匹配的"a"依次替换为递增的数字。

修正后的脚本

tell application "Adobe InDesign 2023"
    set myDocument to document 1

    -- 设置查找替换选项
    set include footnotes of find change text options to false
    set include hidden layers of find change text options to false
    set include locked layers for find of find change text options to false
    set include locked stories for find of find change text options to false
    set include master pages of find change text options to false
    set whole word of find change text options to false
    set case sensitive of find change text options to true
    set search backwards of find change text options to false

    -- 重置查找替换偏好
    set find text preferences to nothing
    set change text preferences to nothing

    set mySelection to selection
    tell myDocument
        set myCharacterStyle to character style "sup" of character style group "Cross References"
    end tell

    -- 定义数字序列(对应15个替换项)
    set myNumbers to {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"}

    -- 先收集所有带sup样式的"a"文本对象
    set find what of find text preferences to "a"
    set applied character style of find text preferences to myCharacterStyle
    set foundItems to find text mySelection

    -- 逐个替换每个匹配项
    repeat with i from 1 to count of foundItems
        if i ≤ count of myNumbers then
            set contents of item i of foundItems to item i of myNumbers
            -- 重新应用字符样式(替换文本可能丢失样式)
            set applied character style of item i of foundItems to myCharacterStyle
        end if
    end repeat
end tell

关键修改说明

  • 先通过find text获取所有匹配的文本对象列表foundItems,避免批量替换一次性清空所有目标内容。
  • 遍历foundItems逐个替换,确保每个匹配的"a"对应递增的数字。
  • 替换后重新应用sup字符样式,防止文本替换导致样式丢失。
  • 增加长度判断,避免数字列表长度不足时触发错误。

内容的提问来源于stack exchange,提问作者GarryTN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 01:15:33