I made a program to display Google Translate and the original English sentence side by side using googletrans, a package for using Google Translate in Python.
I wanted to make a file that arranged English and Japan translated by Google. I wanted to try it easily, so I decided to make it in Python.
When I searched, I found such a site. Python – I tried googletrans. | Developers.IO
Published on PyPI. googletrans · PyPI
Googletrans is a free and unlimited python library that implemented Google Translate API. This uses the Google Translate Ajax API to make calls to such methods as detect and translate.
For some reason, it's free. Is that okay? There seem to be some restrictions.
By the way, Google's Translation API is charged. Cloud Translation Docs | Google Cloud
I was able to install it with the following command.
~$ pip3 install googletrans
Each version of the implementation environment is as follows.
~$ python3 --version
Python 3.5.3
~$ pip3 list | grep google
googletrans (2.4.0)
I made the following program. Input an English text file with command line arguments and output the source text and translation results to standard output.
translate.py
from googletrans import Translator
import sys
args= sys.argv
if len(args) < 2:
print('Command should be like')
print('python3 translate.py textfile.txt')
else:
print('open '+args[1])
f = open(args[1])
lines = f.readlines()
f.close()
translator = Translator()
for line in lines:
translated = translator.translate(line, dest="ja");
print(line) # English
print(translated.text) # Japanese
print()
print('finished')
You can input a file written in English with the following command and output a file written in English and Japanese.
python3 translate.py file_en.txt > file_jp.txt
The input file and its result are as follows.
file_en.txt
Hello,
World.
file_jp.txt
file_en.txt
Hello,
Hello,
World.
world.
finished
When I checked other sentences, the result of translation using the browser's Google Translate add-in was different from the result of translation using googletrans.
It was easy to make. Python, Google and googletrans are great. In the future, I would like to compare by doing similar things within the free frame of the original API. It seems to be free up to 500,000 characters / month. See the site below. Cloud Translation | Google Cloud Free translation API in 3 minutes with Google Apps Script --Qiita How to make Google Translate API for free --Qiita
Recommended Posts