[Python] Hit the Google Translation API

A script that translates English sentences into Japanese. It is a class of former code. I created it because the distributed library didn't work well.

You need to get the API Key of Google Cloud. (You can do it right away)

google_translate.py


import requests
import json
import time

class GoogleTranslate:
    def __init__(self):
        self.private_key = '<Put the API Key here>'

    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:
                #Send to google if it exceeds 1000 characters
                translated_text += self.post_text(to_google_sen)
                time.sleep(3)

                to_google_sen = ""

            if index == len(sen_list)-2:
                #Translation of the last sentence
                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+='.'
            #.If it does not end with, it will interfere with the division process.
        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('Please convert to English and enter the word you want to search in Japanese:')
google_tr = GoogleTranslate()
translated = google_tr.main(input_text)

print(translated)

Recommended Posts

[Python] Hit the Google Translation API
Hit the Sesami API in Python
Hit the Etherpad-lite API with Python
Hit the web API in Python
Python beginners hit the unofficial API of Google Play Music to play music
How to use the Google Cloud Translation API
Hit the Firebase Dynamic Links API in Python
Hit Mastodon's API in Python
Call the API with python3.
Google Drive Api Tips (Python)
PHP and Python samples that hit the ChatWork API
Getting the arXiv API in Python
[Python3] Google translate google translate without using api
Use the Flickr API from Python
Access the Twitter API in Python
Use Google Analytics API from Python
An easy way to hit the Amazon Product API in Python
Hit the New Relic API in Python to get the server status
Regularly upload files to Google Drive using the Google Drive API in Python
Google Cloud Vision API sample for python
Try using the Wunderlist API in Python
Try using the Kraken API in Python
Tweet using the Twitter API in Python
Get Google Fit API data in Python
Use Google Cloud Vision API from Python
Get holidays with the Google Calendar API
Try hitting the YouTube API in Python
Creating Google Spreadsheet using Python / Google Data API
Japanese translation: PEP 20 --The Zen of Python
Hit Zabbix API (1.8, 2.0)
Hit a method of a class instance with the Python Bottle Web API
Created a Python wrapper for the Qiita API
Hit the Web API using requests Example: Flickr
Run Google Analytics API (core v3) in python
Try using the BitFlyer Ligntning API in Python
I tried using the Google Cloud Vision API
Tweet (API 1.1) on Google App Engine for Python
Tips for hitting the ATND API in Python
Until you can use the Google Speech API
Try accessing the YQL API directly from Python 3
Try using the DropBox Core API in Python
[GCP] [Python] Deploy API serverless with Google Cloud Functions!
Find the maximum Python
[Python] Get the text of the law from the e-GOV Law API
Hit the Twitter API after Oauth authentication with Django
Initial settings when using the foursquare API in python
the zen of Python
Evernote API in Python
[Python] Get insight data using Google My Business API
Send and receive Gmail via the Gmail API using Python
OpenCV3 Python API list
A story about a Python beginner trying to get Google search results using the API
Let's use the Python version of the Confluence API module.
Create a tweet heatmap with the Google Maps API
[Translation] 25 year old Python
Hit Watson's REST API from Python on IBM Bluemix
[Python] Split the date
Speech transcription procedure using Python and Google Cloud Speech API
Using the National Diet Library Search API in Python
C API in Python 3
TensorFlow API memo (Python)