LoginSignup
31
33

More than 3 years have passed since last update.

Pythonでgoogletransを使って翻訳

Last updated at Posted at 2020-03-03

概要

Pythonでグーグル翻訳を使うためのパッケージgoogletransを使って、グーグル翻訳と元の英語の文章を並べて表示するプログラムを作った。

はじめに

英語とグーグル翻訳した日本を並べたファイルを作りたかった。手軽に試してみたかったのでPythonで作ることにした。

調査

検索すると、こんなサイトを見つけた。
Python – googletransを試してみました。 | Developers.IO

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.

なぜか、フリー。いいんかな?制約はいくつかあるみたい。

ちなみに、GoogleのTranslation APIは有料。
Cloud Translation ドキュメント  |  Google Cloud

環境

下記コマンドでインストールできた。

~$ pip3 install googletrans

実施環境の各バージョンは下記の通り。

~$ python3 --version
Python 3.5.3
~$ pip3 list | grep google
googletrans (2.4.0)

プログラム

以下のようなプログラムを作った。
コマンドライン引数で、英語のテキストファイルを入力して、原文と翻訳結果を標準出力に出す。

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')

実行

下記コマンドで英語の書かれているファイルを入力して、英語と日本語訳の書かれているファイルを出力できる。

python3 translate.py file_en.txt > file_jp.txt

入力ファイルとその結果は以下の通り。

file_en.txt
Hello,
World.
file_jp.txt
file_en.txt
Hello,

こんにちは、

World.

世界。

finished

他の文章も確認したところ、ブラウザのグーグル翻訳のアドインで翻訳した訳と、googletransを使って翻訳した結果が違った。

おわりに

簡単に作れた。PythonとGoogleとgoogletransすばらしい。
今後、本家のAPIの無料枠内で似たようなことやって比較したい。
50万文字/月までは無料らしい。下記サイト参照。
Cloud Translation  |  Google Cloud
3 分で作る無料の翻訳 API with Google Apps Script - Qiita
Google翻訳APIを無料で作る方法 - Qiita

31
33
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
33