LoginSignup
2
9

More than 5 years have passed since last update.

GoogleCloudPlatform Natural Language API の導入から、使い方まで

Last updated at Posted at 2017-05-20

GoogleCloudPlatform Natural Language API の導入から、使い方まで

  • 完全に私の備忘録です。GoogleCloudPlatformをGCPと表現します。Mac OS Sierraを用いています。

SDKをダウンロード

  • virtualenvで2.7系を入れてから、実行する

  • 認証まで。

export GOOGLE_APPLICATION_CREDENTIALS="/Users/users/hoge/key.json"

Google Cloud Natural Language APIの準備

python バインディング

https://github.com/GoogleCloudPlatform/google-cloud-python python3.6も対応している


pip install --upgrade google-cloud
gcloud auth application-default login
  • API 情報はここでみよう!!!

  • api tutorial

https://googlecloudplatform.github.io/google-cloud-python/stable/language-usage.html
を参考に、以下のように便利クラスを作ります:

from google.cloud import language
class GCNaturalLanguage(object):
    def __init__(self, upper=10000):
        # Instantiates a client
        self.client = language.Client()
        self.upper = upper

    def get_entity(self, text):
        length = len(text)

        if length > self.upper:
            print("{} .. too long".format(length))
            return {}

        document = self.client.document_from_text(text, language='ja')

        # Detects the sentiment of the text
        res = document.analyze_entities()
        print("{} characters => done!".format(len(text)))
        dic = {}
        for entity in res.entities:

            for m in entity.mentions:
                dic.update({m.text.begin_offset: m.text.content})

        return dic

例)

import GCNaturalLanguage
gcn = GCNaturalLanguage()
dic = gcn.get_entity("アクセス解析でクロスドメインを設定してみた")
print(dic)
# 21 characters => done!
# {0: 'アクセス解析', 7: 'クロスドメイン'}

ちなみに、MeCabでは、

# 拡張辞書としてポピュラーなmecab-ipadic-neologd を利用してます
$ mecab -d /usr/local/lib/mecab/dic/mecab-ipadic-neologd
アクセス解析でクロスドメインを設定してみた
アクセス解析  名詞,固有名詞,一般,*,*,*,アクセス解析,アクセスカイセキ,アクセスカイセキ
で 助詞,格助詞,一般,*,*,*,で,デ,デ
クロス   名詞,サ変接続,*,*,*,*,クロス,クロス,クロス
ドメイン    名詞,一般,*,*,*,*,ドメイン,ドメイン,ドメイン
を 助詞,格助詞,一般,*,*,*,を,ヲ,ヲ
設定  名詞,サ変接続,*,*,*,*,設定,セッテイ,セッテイ
し 動詞,自立,*,*,サ変・スル,連用形,する,シ,シ
て 助詞,接続助詞,*,*,*,*,て,テ,テ
み 動詞,非自立,*,*,一段,連用形,みる,ミ,ミ
た 助動詞,*,*,*,特殊・タ,基本形,た,タ,タ
EOS

となりました。
「アクセス解析」は前者、後者ともうまく言っていることがわかります。(ちなみに、mecab-ipadic-neologdを引数に取らず、直接mecabとして、形態素解析を行なった場合は、「アクセス」と「解析」が分離してしまうという事態が起こってしまいます)

しかし、例えば、「クロスドメイン」という専門用語を抜き出したい場合は、MeCabでは直接抜き出せないので、外部ツールであるGCP Natural Language APIを用いると、目的が達成されることになります。
この先の使用方法としては、GCPで抜き出せたものを新語としてユーザー辞書登録した上で、MeCabを再度利用するというような感じで使って見ると良いです1

2
9
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
2
9