LoginSignup
4
7

【Python】PythonからGoogle翻訳を使ってみたらあまりにも簡単だった

Last updated at Posted at 2020-04-19

Pythonのパッケージgoogletransを使って翻訳をしてみたら、あまりにも簡単だったので書き留めておきます。

googletransとは

pythonでgoogle翻訳を使うならGoogle Translate APIを使えばいいじゃん。

って思うかもしれませんが、これお金かかるんですよね。
セコい話ですけどお金かけずに遊び感覚でpythonからGoogle翻訳使いたかったんです。

いろいろ調べてたらgoogletransなるものがあったので使ってみようと思いました。

googletransの特徴

  • 無料
  • Google翻訳に文字列をHTTPで渡す
  • 1つのテキストの最大文字数は15k
  • google translateのウェブバージョンの制限により、このAPIはライブラリが常に適切に動作することを保証しない
  • つまり安定性が必要ならGoogle Translate APIを使った方がいい

ざっとこんな感じ。
では早速パッケージをインストールしていくところから説明します。

googletransのインストール

以下のコマンドをコンソールに入力して、Enterキーを押すだけ。

pip install googletrans

超簡単。

googletransを使って翻訳してみる

trans.py
from googletrans import Translator

str = 'これはバナナです。' #翻訳したい文字

translator = Translator()
trans_text = translator.translate(str) #デフォルトでは英語へ変換
print(trans_text.text)

基本的な使い方はこんな感じ。


translate(str)のところはオプションをつけることによって翻訳先の言語を指定することも可能。

trans.py
from googletrans import Translator

str = 'これはバナナです。' #翻訳したい文字

translator = Translator()
trans_text = translator.translate(str,src='ja',dest='de') #日本語からではドイツ語へ変換
print(trans_text.text)

翻訳したい文字列にはリストも渡せるみたいです。 > ``` >>> translations = translator.translate(['The quick brown fox', 'jumps over', 'the lazy dog'], dest='ko') >>> for translation in translations: ... print(translation.origin, ' -> ', translation.text) # The quick brown fox -> 빠른 갈색 여우 # jumps over -> 이상 점프 # the lazy dog -> 게으른 개 ``` >

まとめ

ざっとではありますがGoogle翻訳を使えるPythonパッケージ「googletrans」をご紹介しました。
特徴としては

  • 無料
  • 安定性に欠ける
  • 記述量が少ない

こんな感じでしょうか。以上です。

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