Read English sentences by hitting Google Translate API with Python without using the distributed module

It seems that the accuracy of Google Translate is getting higher and higher. I think there are situations where you have a large amount of English sentences at hand and want to translate them into Japanese. Until I wrote this Qiita, I thought that the spelling of translate was translate, but by hitting the API, even such a weak person will be able to read English sentences.

Cloud Translation Document

The officially distributed Python client library didn't work well in my environment, so I was having trouble. I decided to hit it without using this module. Please refer to other sites for Google Cloud registration and API key acquisition method.

We have confirmed that it works in the following two environments at hand.

Mac OS Mojave chardet(3.0.4) requests(2.18.4) urllib3(1.22)

Ubuntu 18.04 chardet (3.0.4) requests (2.22.0) urllib3 (1.25.7)

translate.py


import requests
import json
import time

private_key = '<Put your API KEY here>'

def post_text(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(private_key), data=item_data)
    # print(response.status_code)
    #Status code
    # print(response.text)
    #Get the response as a string
    return json.loads(response.text)["data"]["translations"][0]["translatedText"]

    
def split_and_send_to_post(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 += post_text(to_google_sen)
            time.sleep(3)
            
            to_google_sen = ""

        if index == len(sen_list)-2:
            #Translation of the last sentence
            translated_text += post_text(to_google_sen)
            time.sleep(3)

    return translated_text
        

if __name__ == '__main__':

    original_text = "I hope this sentence is transrated."
    if original_text[-1] != '.':
        original_text+='.'
        #.If it does not end with, the division process will be hindered.
    text_translated = split_and_send_to_post(original_text)
    print(text_translated)

If the sentence is too long, an error will occur on the Google side, so I will divide it into about 1000 characters and send it. (I think that an insanely long sentence that does not use. Will cause an error. It is assumed for normal use.) Also, from v3, it seems that you can not hit with the API key, so I am using v2.

Execution result

$ python translate.py
I hope this sentence is translated.

reference Cloud Translation API

Recommended Posts

Read English sentences by hitting Google Translate API with Python without using the distributed module
I tried using the Datetime module by Python
Speech file recognition by Google Speech API v2 using Python
Play music by hitting the unofficial API of Google Play Music
I tried hitting the API with echonest's python client
Try hitting the Twitter API quickly and easily with Python
A note about hitting the Facebook API with the Python SDK
Why can I use the module by importing with python?
Inflating text data by retranslation using google translate in Python
Get an English translation using python google translate selenium (memories)
Call the API with python3.
Play with YouTube Data API v3 using Google API Python Client
Create an application that just searches using the Google Custom Search API with Python 3.3.1 in Bottle
Regularly upload files to Google Drive using the Google Drive API in Python
Play by hitting the Riot Games API in Python First half
[Python] Hit the Google Translation API
Hit the Etherpad-lite API with Python
[python] Read information with Redmine API
Try using the Python Cmd module
Install the python module with pip on a server without root privileges
Create a record with attachments in KINTONE using the Python requests module
[Implementation example] Read the file line by line with Cython (Python) from the last line
Try using the Wunderlist API in Python
Try using the Kraken API in Python
Behind the flyer: Using Docker with Python
Try using Python with Google Cloud Functions
Let's read the RINEX file with Python ①
Working with OpenStack using the Python SDK
Read the file line by line in Python
Get holidays with the Google Calendar API
Try hitting the YouTube API in Python
Play with puns using the COTOHA API
Creating Google Spreadsheet using Python / Google Data API
[Python] Automatically totals the total number of articles posted by Qiita using the API
To automatically send an email with an attachment using the Gmail API in Python
Ask the bot to tell you the weather (precipitation information) using the weather information API (YOLP) provided by Yahoo ~ slack bot development with python ④ ~
Python script that throws English sentences such as man that are disturbing by spaces and line breaks to Google Translate
[Python] Let's execute the module regularly using schedule
Try using the BitFlyer Ligntning API in Python
I tried using the Google Cloud Vision API
Tips for hitting the ATND API in Python
Specifying the module loading destination with GAE python
Recent ranking creation using Qiita API with Python
Try using the collections module (ChainMap) of python3
Read line by line from a file with Python
Examine Python script bottlenecks with the cProfile module
Try using the DropBox Core API in Python
[Python] You can save an object to a file by using the pickle module.
Second half of the first day of studying Python Try hitting the Twitter API with Bottle
A story about a Python beginner trying to get Google search results using the API
Various memorandums when using sdk of LINE Messaging API with Python (2.7.9) + Google App Engine