Python で、Watson の翻訳サービスを使う


Watson の翻訳サービスを、Python3 の request で使う例と、SDK で使う例です。
username と password は変更して下さい。

request の 例

translate_request.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#       translate_request.py
#
#                                       Aug/14/2017
# --------------------------------------------------------------------
import sys
import requests
# --------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
username="12346e5d-350f-4fa5-b991-8dc6bb578789"
password="AB7tL8knaOTZ"
url_v2="https://gateway.watsonplatform.net/language-translator/api/v2"
#
word_in = "I got up early today."
url_en_ja=url_v2 + "/translate?model_id=en-ja&text="
url_target = url_en_ja + word_in
rr=requests.get(url_target,auth=(username,password))
print(rr.text)
#
#
word_in = "今日は早起きした。"
url_ja_en=url_v2 + "/translate?model_id=ja-en&text="
url_target = url_ja_en + word_in
rr=requests.get(url_target,auth=(username,password))
print(rr.text)
#
sys.stderr.write("*** 終了 ***\n")
# --------------------------------------------------------------------

SDK の例

translate_sdk.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   translate_sdk.py
#
#                       Aug/13/2017
#
# --------------------------------------------------------------------
import sys
import json
from watson_developer_cloud import LanguageTranslatorV2
# --------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
language_translator = LanguageTranslatorV2(
    username='12346e5d-350f-4fa5-b991-8dc6bb578789',
    password='AB7tL8knaOTZ')
#
result = language_translator.translate('I got up early today.', source='en',
        target='ja')
print(result)
#
result = language_translator.translate('今日は早起きした。', source='ja',
        target='en')
print(result)
#
sys.stderr.write("*** 終了 ***\n")
# --------------------------------------------------------------------