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