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.
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