Googleスプレッドシートで日本語の読みがなを自動取得する方法(よみたんAPI v2+GAS)

Googleスプレッドシートで日本語の読みがなを自動取得したい場合、Google Apps Script(GAS)から「よみたんAPI」を呼び出す方法があります。

よみたんAPIは、GETリクエストでクエリを渡すと読みがなを返してくれるWeb APIです。Googleスプレッドシートのカスタム関数として設定すれば、セルに入力した語句の読みがなを別のセルに表示できます。

GASコード

以下は、Googleスプレッドシート上で使えるカスタム関数の例です。

/**
* 指定された文字列の読みがなを返却します。
*
* このコードは、よみたんAPI v2をGoogle Apps Scriptから利用して、
* 日本語文字列の読みがなを取得するサンプルです。
*
* よみたんAPIを使用しています。
* API提供元:よみたん(HARMONICOM)
*
* 注意:
* 大量のセルで常時再計算させるとAPIに負荷がかかる可能性があります。
* 読みがな取得後は、必要に応じて値貼り付けにするなど、
* 過度な連続アクセスを避けてください。
*
* @param {string} word 日本語文字列
* @param {string} kquery "h" ひらがな / "k" カタカナ
* @return {string} 変換後の文字列
* @customfunction
*/
function GetPhonetic(word, kquery = "h") {
  if (!word) return "";

  // よみたんAPI v2を使用しています
  // https://yomitan.harmonicom.jp/api/v2/yomi
  const url =
    "https://yomitan.harmonicom.jp/api/v2/yomi" +
    "?ic=UTF8" +
    "&oc=UTF8" +
    "&kana=" + encodeURIComponent(kquery) +
    "&num=3" +
    "&text=" + encodeURIComponent(word);

  const response = UrlFetchApp.fetch(url, {
    muteHttpExceptions: true
  });

  const code = response.getResponseCode();
  if (code !== 200) {
    return "ERROR " + code;
  }

  const json = JSON.parse(response.getContentText());

  // 応答の yomi 配列から1個目の読みを取得
  if (!json.yomi || json.yomi.length === 0) {
    return "";
  }

  return json.yomi[0];
}

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

GoodMorning!

デジタルの海原を冒険しながら、美食の宝を探し求める探検家です。テクノロジーの世界を舞台に、新しい発見を求めて、キーボードの海を横断。そして、実世界では、隅々まで足を運んで、舌鼓を打つ価値のある美味しいお店を見つけ出します。

私の使命は、小さなITの豆知識から始まり、心を満たすグルメスポットの紹介まで、あなたの日常にちょっとしたスパイスを加えること。画面の向こう側から、気軽に楽しめる話題を届けたいのです。ここでは、私が「これは!」と思った技術的な小話や、舌の記憶に残るような食べ物屋さんを紹介していきます。

このWebサイトは、ITとグルメ、二つの世界を融合させた、まさにデジタルと現実の融合点。ふらっと立ち寄って、新たな発見や、ほっこりするような話題で一息ついていただけたら幸いです。知識の海を冒険し、味覚の旅を楽しみましょう。毎日を少しだけ特別なものに変える、そんな情報をお届けします。

GoodMorning!

I am an explorer who ventures across the digital sea in search of gastronomic treasures. In the world of technology, I traverse the sea of keyboards in search of new discoveries. And in the real world, I visit every nook and cranny to find a delicious restaurant worth tantalizing your taste buds.

My mission is to add a little spice to your everyday life, starting with little IT tidbits and ending with foodie spots that fill your heart. I want to bring you topics that you can easily enjoy from the other side of the screen. Here, I'm going to share with you some of the technical tidbits and I will introduce small technical stories and food shops that will leave a lasting impression on your taste buds.

This Web site is truly a fusion point of digital and reality, combining the two worlds of IT and gourmet. I hope you will stop by and take a breather with new discoveries and dusty topics. Come explore the sea of knowledge and enjoy a journey of taste. I will bring you the information that will change your everyday life into something a little more special.

目次