Google クラウド自然言語APIを実装する① Pythonを使う
前回は、クラウド自然言語APIをcURLで活用してみましたが、実際のサービスに実装するにはどうしたらいいのかなと、困っていました。
弊社の天才エンジニア救世主に教えを被り、順調に進めることができました。横でコーディングを見ているとマジで惚れます。萌えます。あーー。
Google先生が、GitHubにPythonを使ったクラウド自然言語APIの実装例が載せていたので、これを参考にしながら、進めていきます。
python-docs-samples/language/api at master · GoogleCloudPlatform/python-docs-samples · GitHub
まずは、Python環境を作る
1) pyenvをインストール
pyenvとは、Pythonの様々なversionの環境を作ることができるもの。githubからインストールすると、home下に環境が作られます。
pyenv lets you easily switch between multiple versions of Python. It's simple, unobtrusive, and follows the UNIX tradition of single-purpose tools that do one thing well.
というわけで、terminalを立ち上げてコマンド入力。
cd $HOME
git clone https://github.com/yyuu/pyenv.git ~/.pyenv
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
echo 'eval "$(pyenv init -)"' >> ~/.bash_profile
exec $SHELL
pyenv install 2.7.12
pyenv global 2.7.12
pyenv rehash
これで、home下にpython環境ができました。
2) pythonの基本文法
.py : Python fileの拡張子
import : ライブラリー呼び出し
def xxxx(): :関数定義
if __name__ == '__main__': :起動プログラム。これがないと何も動かない
3) terminalで動かす
Python fileのあるディレクトリーまで移動し、そこで、以下を叩くことでファイルが起動されます。print()で出力することができます。
python test.py
こんな感じでござる。