Python – googletransを試してみました。
ベルリンの半瀬です。
冷えますね。
はじめに
google翻訳をお手軽に使えないかと思ってグーグルしたら、pythonパッケージ googletrans というものを見つけましたので、動作確認をしてみました。
googletrans
- Google翻訳に文字列をhttpで渡して翻訳する(タダで使える
- python2.7以上、python3.4以上でサポート
- python2のサポートは次のメジャーリリース時に終了予定
確認内容
インストール
python3で試しました。
1 2 | % python -VPython 3.6.2 |
pipインストール
1 | % pip install googletrans |
基本動作
srcで翻訳元の言語を指定、destで翻訳先の言語を指定します。
destで何も指定しなければ、デフォルトは英語訳(en)となる様です。
1 2 3 4 5 | >>> from googletrans import Translator>>> translator = Translator()>>> print(translator.translate('Blühe, deutsches Vaterland'))Translated(src=de, dest=en, text=Blossom, German fatherland, pronunciation=Blossom, German fatherland)>>> |
destに日本語jaを指定します。
日本語はうまくないですね。。。
1 2 3 4 5 | >>> from googletrans import Translator>>> translator = Translator()>>> print(translator.translate('Blühe, deutsches Vaterland', dest='ja'))Translated(src=de, dest=ja, text=花、ドイツの祖国, pronunciation=None)>>> |
日本語からドイツ語に変換する。
1 2 3 4 5 | >>> from googletrans import Translator>>> translator = Translator()>>> print(translator.translate('ベルリンの壁', src='ja' ,dest='de'))Translated(src=ja, dest=de, text=Berliner Mauer, pronunciation=None)>>> |
その他
発展的な使い方を少々。
リストで入出力。
1 2 3 4 5 6 7 8 9 | >>> translations = translator.translate(['The Germany national football team', 'wins', 'World Cup 2014.'], dest='de')>>> for translation in translations:... print(translation.text)... Die deutsche FußballnationalmannschaftgewinntWeltmeisterschaft 2014.>>> |
言語検出も可能。
1 2 3 4 5 6 7 8 9 | >>> from googletrans import Translator>>> translator = Translator()>>> print(translator.detect('ダダダ'))Detected(lang=ja, confidence=1)>>> print(translator.detect('la vecchia signora'))Detected(lang=it, confidence=1)>>> print(translator.detect('This is a pen'))Detected(lang=en, confidence=1)>>> |
さいごに
googletransの動作を確認しました。注意点は以下のとおりです。
- テキストは最大15kまで
- Google翻訳の制限に依存し、このライブラリはいつでも利用可能とは限らない
- 安定性が必要な場合は有料のGoogle’s official translate APIを使いましょう
詳細はコチラ
ではまた