Natural Language API に直接送信されたテキスト文字列に対して感情分析を行う例を次に示します。
感情分析を行う関数の定義
入力した文章全体に対する感情と1文ずつの感情を取得して、それぞれ表示するプログラムを作成します。
from google.cloud import language_v1
from google.cloud.language_v1 import enums
from google.cloud.language_v1 import types
def sample_analyze_sentiment(text_content):
"""
Analyzing Sentiment in a String
Args:
text_content The text content to analyze
"""
client = language_v1.LanguageServiceClient()
type_ = language_v1.types.Document.Type.PLAIN_TEXT
document = types.Document(
content=text_content,
type=enums.Document.Type.PLAIN_TEXT)
response = client.analyze_sentiment(document=document)
# Get overall sentiment of the input document
print(u"Document sentiment score: {}".format(response.document_sentiment.score))
print(
u"Document sentiment magnitude: {}".format(
response.document_sentiment.magnitude
)
)
# Get sentiment for all sentences in the document
for sentence in response.sentences:
print(u"Sentence text: {}".format(sentence.text.content))
print(u"Sentence sentiment score: {}".format(sentence.sentiment.score))
print(u"Sentence sentiment magnitude: {}".format(sentence.sentiment.magnitude))
# the automatically-detected language.
print(u"Language of the text: {}".format(response.language))