LoginSignup
6
11

More than 5 years have passed since last update.

Google Translation API 利用メモ【Python】

Last updated at Posted at 2017-10-30

セットアップ

クライアントのインストール

pip install --upgrade google-api-python-client
easy_install --upgrade google-api-python-client

サービスアカウントキー(jsonファイル)を取得

Google Cloud Platfrom -> APIとサービス -> 認証情報
1.認証情報の作成
2.サービスアカウントキーで新しいサービスアカウントキーとjsonを選択 -> 役割はProjectのオーナーにしておけば全権得られるらしいので、それにしておいて適当な名前をつけて作成
3.jsonファイルゲット。これをクローラープログラムのあるところに移動しておく

Clowd SDKをインストール

https://cloud.google.com/sdk/docs/quickstart-mac-os-x
からインストール
このサイトの解説がわかりやすい

クライアントライブラリのインストール

pip install --upgrade google-cloud-translate

サンプルプログラム

https://cloud.google.com/translate/docs/reference/libraries#client-libraries-install-python がお手本。
環境変数の設定がうまく行かなかったので、コードの中で定義するようにした。

# Imports the Google Cloud client library
from oauth2client.client import GoogleCredentials
from google.cloud import translate
import os

# add environment variable
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "jsonまでのpath"

# Certification
credentials = GoogleCredentials.get_application_default()
# Instantiates a client
translate_client = translate.Client()

# The text to translate
text = u'Hello, world!'
# The source and target language
trans_from = 'en'
trans_to = 'ja'

# Translates some text into Japanese
translation = translate_client.translate(text, source_language=trans_from, target_language=trans_to, model='nmt')

print(u'Text: {}'.format(text))
print(u'Translation: {}'.format(translation['translatedText']))
print(translation)
6
11
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
6
11