文書中の単語の出現回数を集計するONLYOFFICEマクロの作り方

2024年05月23日著者:Denis

コンテンツを監査する場合でも、重要な単語を調べる場合でも、データをより深く理解する場合でも、単語の出現頻度を知ることはとても便利です。この記事では、文書内で特定の単語が出現する回数をカウントするマクロの作成方法をご紹介します。

Building an ONLYOFFICE macro to tally word occurrences in your document

マクロの構築

(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ファイルの閲覧、編集、共同作業