pikesaku’s blog

個人的な勉強メモです。記載内容について一切の責任は持ちません。

Natural Language API気づいた点

APIレスポンス情報の取り方。
こんな取り方もできた。UNKNOWNは出力されない。
json形式でも取得できる。

インプットテキスト

私は犬です。


サンプルコード

# -*- coding: utf-8 -*-
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types
import six
import sys
def syntax_text(text):
    """Detects syntax in the text."""
    client = language.LanguageServiceClient()
    if isinstance(text, six.binary_type):
        text = text.decode('utf-8')
    document = types.Document(
        content=text,
        type=enums.Document.Type.PLAIN_TEXT)
    tokens = client.analyze_syntax(document).tokens
#    for token in tokens:
#        print(token)
    for token in tokens:
        print(u'{}: Ofset: {} Part_Of_Speech: {} Dependency_Edge: {}'.format(token.text.content, token.text.begin_offset, ' '.join(str(token.part_of_speech).splitlines()), to
ken.dependency_edge.head_token_index))
def main():
    text = '私は犬です。'
    syntax_text(text)
main()


実行結果

私: Ofset: -1 Part_Of_Speech: tag: PRON person: FIRST proper: NOT_PROPER Dependency_Edge: 2
は: Ofset: -1 Part_Of_Speech: tag: PRT proper: NOT_PROPER Dependency_Edge: 0
犬: Ofset: -1 Part_Of_Speech: tag: NOUN proper: NOT_PROPER Dependency_Edge: 2
です: Ofset: -1 Part_Of_Speech: tag: VERB form: FINAL_ENDING proper: NOT_PROPER Dependency_Edge: 2
。: Ofset: -1 Part_Of_Speech: tag: PUNCT proper: NOT_PROPER Dependency_Edge: 2