[A-00091]pythonでTranslation API(GCP)を使用する
Google Cloudが提供するTranslation APIをpythonで使用する方法を記載しておく。
公式ドキュメントはこちら
https://cloud.google.com/translate/docs/reference/libraries/v3/overview-v3
・セットアップ
pythonライブラリをインストールします。
pip install --upgrade google-cloud-translate
・日本語テキストを英語に変換する
pythonから日本語テキストを渡し、それを英語に変換します。
from google.cloud import translate
def translate_text(text="これは良い楽器ですね", project_id="<project_id>"):
client = translate.TranslationServiceClient()
location = "global"
parent = f"projects/{project_id}/locations/{location}"
response = client.translate_text(
request={
"parent": parent,
"contents": [text],
"mime_type": "text/plain",
"source_language_code": "ja-JP",
"target_language_code": "en-US",
}
)
for translation in response.translations:
print("Translated text: {}".format(translation.translated_text))
translate_text()
(.venv)MacBook-Pro:test2_project$ python3 translatetest.py
Translated text: this is a good instrument
上記の通り、日本語から英語に変換できました。
コメントを残す