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

如何在Google Docs脚本中定位Standard Pilish文本的首个错误单词

修正Google Docs Apps Script的Standard Pilish检查计数错误

问题核心

开发Standard Pilish规范检查脚本时,存在两个关键问题:

  • 文本处理逻辑错误,导致原本的单个单词被拆分成多个,使得单词数组索引与实际单词不匹配
  • 获取的错误位置为数组格式,直接用该位置取单词时,无法对应到实际错误的单词

修正后的脚本

function pilishTranslate() {
  var doc = DocumentApp.getActiveDocument();
  var text = doc.getBody().getText();
  
  // 修正文本处理:保留单词内的撇号,去除引号后拆分有效单词
  text = text.replace(/[""]/g, '');
  var words = text.split(/\s+/).filter(word => /[a-zA-Z]/.test(word));
  
  // 转换单词长度为Pilish规则对应的数字(10→0)
  var wordLengths = words.map(word => {
    const len = word.length;
    return len === 10 ? 0 : len;
  });
  
  var wordLengthsString = wordLengths.join('');
  const decimal15 = '314159265358979'; // 圆周率前15位

  // 计算最长公共前缀长度
  const getCommonPrefixLength = (a, b) => {
    let i = 0;
    while (i < a.length && i < b.length && a[i] === b[i]) i++;
    return i;
  };

  // 获取首个不匹配的位置
  const getFirstMismatchPos = (a, b) => a === b ? -1 : getCommonPrefixLength(a, b);
  const mismatchPos = getFirstMismatchPos(wordLengthsString, decimal15);

  if (mismatchPos === -1) {
    console.log("文档完全符合Standard Pilish规范");
    return;
  }

  // 提取错误详情
  const errorWord = words[mismatchPos];
  const expectedDigit = decimal15[mismatchPos];
  const actualLen = errorWord.length;
  const expectedLen = expectedDigit === '0' ? 10 : parseInt(expectedDigit);

  console.log(`首个错误:第${mismatchPos + 1}个单词`);
  console.log(`错误单词:${errorWord}`);
  console.log(`预期单词长度:${expectedLen}(对应圆周率数字${expectedDigit})`);
  console.log(`实际单词长度:${actualLen}`);
}

关键修改点

  • 文本处理优化:保留英文单词常见的撇号,拆分后过滤空字符串,确保words数组仅包含有效单词,避免索引偏移
  • 错误位置映射修正:差异位置直接对应words数组的索引(每个单词对应wordLengthsString的一个字符,索引完全匹配)
  • 逻辑简化:用循环替代递归计算公共前缀,提升性能和可读性
  • 错误信息增强:输出错误单词的序号、内容、预期长度和实际长度,便于定位问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:01:05