如何创建 ONLYOFFICE 宏来统计文档中单词出现的次数

2024年05月23日作者: Mona

无论是审核内容、查看重要单词,还是只是想更好地理解数据,了解单词出现的频率都十分有益。在本文中,我们会介绍如何创建一个宏,计算特定单词在文档中显示的次数。

如何将 ONLYOFFICE 协作空间的公共房间嵌入到其他网站

创建

(function () {
  const oDocument = Api.GetDocument();
  const oRange = oDocument.GetRangeBySelect();
  const targetWord = "apple";

首先,我们在 oDocument 变量中获取工作文档,在 oRange 中获取文本选择。targetWord 变量包含要搜索的单词。这应该替换为要在文档中搜索的单词。

    const rawText = oRange.GetText();
    var wordRegex = new RegExp("\\b" + targetWord + "\\b", "gi");
    var matches = rawText.match(wordRegex);

接下来,将所选内容中的文本提取到 rawText 中。 正则表达式检查整个文档中的指定单词。此正则表达式存储在 wordRegex 中。然后,使用 match 方法和 wordRegex,我们将 targetWord 的所有实例存储在 matches 数组中。

    let count = 0;
    for (let i = 0; i < matches.length; i++) {
      count++;
    }
    const wordInstances = count;

targetWord 的长度是计算并存储 wordInstances 变量的。

    return wordInstances;
  }

该函数通过在其作用域末尾返回 wordInstances 变量来结束。

  const ans = addCommentToWord();
  oRange.AddComment(
    `The word ${targetWord} is repeated ${ans} times throughout this text.`
  );

最后,我们将函数的返回值存储在 ans 中,并附有一条注释,详细说明了所选内容中重复单词的总实例数。

完整的宏代码

下面是宏的完整代码:

(function () {
  const oDocument = Api.GetDocument();
  const oRange = oDocument.GetRangeBySelect();
  const targetWord = "apple";

  function addCommentToWord() {
    const rawText = oRange.GetText();

    // Specify the target word and the length of the word
    // Find all occurrences of the target word in the document
    var wordRegex = new RegExp("\\b" + targetWord + "\\b", "gi");
    var matches = rawText.match(wordRegex);

    let count = 0;
    for (let i = 0; i < matches.length; i++) {
      count++;
    }
    const wordInstances = count;
    return wordInstances;
  }

  // `The word `${targetword} has been repeated ${wordInstances} times.`
  const ans = addCommentToWord();

  oRange.AddComment(
    `The word ${targetWord} is repeated ${ans} times throughout this text.`
  );

})();

让我们来运行这个这个宏:

这个宏将使文档分析变得轻而易举,毫不费力地计算单词出现次数,提升整体工作流程,简化和完善内容评估。

不要错过利用 ONLYOFFICE API 的机会。我们丰富的API方法库是您将想法变为现实的关键。如果您有任何问题或创新概念,我们鼓励您与我们分享。您的意见非常宝贵,祝您探索成功!

创建免费的 ONLYOFFICE 账户

在线查看并协作编辑文本文档、电子表格、幻灯片、表单和 PDF 文件。