はじめに
今回はgoogle翻訳のAPIであるgoogletransを用いて、英語を日本語に翻訳するプログラムを作成した。その時に学習した内容をここにメモする。
googletransとは
googletransとはGoogle翻訳の文字列をhttp方式で渡すことで翻訳した内容が返ってくるAPIである。今回はこちらを用いた翻訳プログラムをPythonによって作成した。
準備段階
今回の環境ではwsl2にPython3.8.1で行った。まずはpythonのモジュールのインストールについては下記のコマンドによって行った。
pip3 install googletrans==4.0.0rc1
バージョンの指定をしない場合に、googletrans3.0.0がインストールされてしまいそこで躓いた。3.0.0だと 'AttributeError' が生じてしまうため、注意が必要になる。
プログラミング
今回使用したプログラミングを以下に記す。
translate.py
from googletrans import Translator
def translate(text):
translator = Translator()
changetext = translator.translate(text, dest='ja')
return changetext.text
if __name__ == "__main__":
text = 'Nice to meet you'
t = translate(text)
print(t)
プログラミングの内容としては、text内にある文字列を日本語に翻訳しプリントする処理を行う。上記のプログラミングを実行した結果が以下になる。
会えて嬉しい
最後に
今回google翻訳のAPIであるgoogletransを用いた翻訳プログラムを作成した。今後は、このプログラミングを利用し、LINEと組み合わせた翻訳アプリケーションを作成しようと思う。