LoginSignup
0
0

More than 3 years have passed since last update.

Python3: Google Cloud Translation API の使い方 (Advanced)

Last updated at Posted at 2020-11-25

次のページを参考にしました。
テキストの翻訳(Advanced)

ex02.py
#! /usr/bin/python
#
#   ex02.py
#
#                       Nov/25/2020
#
# ------------------------------------------------------------------
import sys
from google.cloud import translate

# ------------------------------------------------------------------
def translate_text(text,project_id):
    """Translating Text."""

    client = translate.TranslationServiceClient()
    location = "global"

    parent = "projects/" + project_id + "/locations/" + location

    response = client.translate_text(
            parent=parent,
            contents=[text],
            mime_type='text/plain',
            source_language_code='de',
            target_language_code='ja')

    for translation in response.translations:
        print("Translated text: {}".format(translation.translated_text))

#
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
project_id = "project-translation"
text="Es war einmal ein kleines Mädchen."
translate_text(text, project_id)
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行方法

export GOOGLE_APPLICATION_CREDENTIALS=./***.json
#
./ex02.py

実行結果

*** 開始 ***
Translated text: 昔々、小さな女の子がいました。
*** 終了 ***

GOOGLE_APPLICATION_CREDENTIALS の作成方法

認証情報 --> サービスアカウントを管理 --> サービスアカウントを作成
service_account_feb13.png

0
0
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
0
0