LoginSignup
1
1

3分でできる!Google 翻訳API

Last updated at Posted at 2023-08-25

alphavantage APIとか使って、以下のような株アプリを作ってる

1. APIコンソールを開く

APIコンソールを開いて、有効化されていることを確認

https://console.cloud.google.com/apis/library?hl=ja

2. サーバに資格認証の設定をする

gcloud auth application-default login

3. pip install

$ pip install google-cloud-translate

4. テストコードを作成


def translate_text(target: str, text: str) -> dict:
    """Translates text into the target language.

    Target must be an ISO 639-1 language code.
    See https://g.co/cloud/translate/v2/translate-reference#supported_languages
    """
    from google.cloud import translate_v2 as translate

    translate_client = translate.Client()

    if isinstance(text, bytes):
        text = text.decode("utf-8")

    # Text can also be a sequence of strings, in which case this method
    # will return a sequence of results for each text.
    result = translate_client.translate(text, target_language=target)

    print("Text: {}".format(result["input"]))
    print("Translation: {}".format(result["translatedText"]))
    print("Detected source language: {}".format(result["detectedSourceLanguage"]))

    return result

translate_text("ja","this is test")

5. 翻訳実行!

$ python3 gcloud_translate.py
Text: this is test
Translation: これはテストです
Detected source language: en
1
1
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
1
1