0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Python】GoogleTranslationAPIを叩く

Last updated at Posted at 2020-02-22

英語の文章を日本語に翻訳するスクリプトです。
以前のコードをクラスにしたものです。配布されているライブラリがうまく動かなかったので作成したものです。

GoogleCloudのAPI Keyは取得していただく必要があります。(すぐできます)

google_translate.py
import requests
import json
import time

class GoogleTranslate:
    def __init__(self):
        self.private_key = '<ここにAPIKeyを入れる>'

    def post_text(self,text):
        url_items = 'https://www.googleapis.com/language/translate/v2'
        item_data = {
            'target': 'ja',
            'source': 'en',
            'q':text
        }

        response = requests.post('https://www.googleapis.com/language/translate/v2?key={}'.format(self.private_key), data=item_data)
        return json.loads(response.text)["data"]["translations"][0]["translatedText"]


    def split_and_send_to_post(self,text):
        sen_list = text.split('.')

        to_google_sen = ""
        translated_text = ""

        for index, sen in enumerate(sen_list[:-1]):
            to_google_sen += sen + '. '
            if len(to_google_sen)>1000:
                #1000字を超えてたらgoogleに送信
                translated_text += self.post_text(to_google_sen)
                time.sleep(3)

                to_google_sen = ""

            if index == len(sen_list)-2:
                #最後の文章の翻訳
                translated_text += self.post_text(to_google_sen)
                time.sleep(1)

        return translated_text


    def main(self,text):
        original_text = text
        if original_text[-1] != '.':
            original_text+='.'
            #.で終わっていない場合に分割処理に支障が出るので
        text_translated = self.split_and_send_to_post(original_text)
        print(text_translated)
        return text_translated
test.py
from google_translate import *

input_text = input('英語に変換して検索したいワードを日本語で入力してください:')
google_tr = GoogleTranslate()
translated = google_tr.main(input_text)

print(translated)
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?