1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

DeepL APIでGoogleスプレッドシートの日本語を英語に翻訳するスクリプト

Last updated at Posted at 2023-02-26

やりたいこと

A列に羅列した日本語をインプットとして、DeepL APIによる英語翻訳結果をB列に出力する。
C列はGoogle翻訳関数(GOOGLETRANSLATE)によるもの。これでもいいが、DeepLのほうがより自然な表現になるためDeepLを使いたい。
image.png

コード

コード.gs
// DeepL APIで使用する認証キー
const apiKey = PropertiesService.getScriptProperties().getProperty('DEEPL_KEY');

/**
 * DeepL翻訳結果を出力する処理。
 * A列の日本語を翻訳し、B列へ英語で出力する。
 */
function translateDeepLja2en() {  
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const numRows = sheet.getLastRow() - 1;
  const sourceRange = sheet.getRange(2, 1, numRows, 1);
  const targetRange = sheet.getRange(2, 2, numRows, 1);
  const sourceValues = sourceRange.getValues().flat();
  const targetValues = sourceValues.map(value => {
    if (value === "") {
      return "";
    } else {
      const translated = translateWithDeepL(value, "JA", "EN");
      return translated.text;
    }
  });

  targetRange.setValues(targetValues.map(value => [value]));
}

function translateWithDeepL(text, sourceLang, targetLang) {  
  const apiUrl = `https://api-free.deepl.com/v2/translate?auth_key=${apiKey}&text=${encodeURIComponent(text)}&source_lang=${sourceLang}&target_lang=${targetLang}`;
  const response = UrlFetchApp.fetch(apiUrl);
  const result = JSON.parse(response.getContentText());
  return result.translations[0];
}

スクリプト以外の設定

const apiKey = PropertiesService.getScriptProperties().getProperty('DEEPL_KEY');で値を取れるようにスクリプトエディタのプロジェクトの設定にある「スクリプトプロパティ」へDeepL API の認証キーを設定する。
プロパティ名:DEEPL_KEY
値:DeepLアカウントページの認証キー
image.png

DeepL翻訳処理を自作関数にした場合の懸念事項

GOOGLETRANSLSTE関数のように、スプレッドシートで利用できる形の関数にすると想定以上にAPIを叩き、DeepL API Freeの上限値50万文字への到達が早まるため避けている。
画面更新やちょっとしたタイミングで画面が更新されるたびに関数が動作している。
自作関数版のコードはDeepLがリポジトリにて公開している。
https://github.com/DeepLcom/google-sheets-example

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?