セットアップ
クライアントのインストール
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)