次のページを参考にしました。
テキストの翻訳(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 の作成方法