1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AzureでTextの感情分析(日本語)

Last updated at Posted at 2022-04-13

概要

Azure Cognitive Service for Language の感情分析を日本語でやってみたい。

前提条件

  • Azure サブスクリプション
  • Python 3.x

準備

Azure サブスクリプションを用意したら、Azure portal で言語リソースを作成して、キーとエンドポイントを取得します。 デプロイされたら、 [リソースに移動] をクリックします。対象のアプリケーションを API に接続するには、作成したリソースのキーとエンドポイントが必要です。 以下で示すコードに、自分のキーとエンドポイントを貼り付けます。※分析機能を使うには、Standard (S) 価格レベルの言語リソースが必要らしいです。

日本語の準備

今日は人生で一番の日でした。君も僕と一緒に入れたらよかったのに。
飯とサービスがダメダメでした。でも、コンシェルジュは良かった。

Azure ML Notebook

ライブラリを2つほどインストールします。

pip install azure-ai-textanalytics==5.1.0
pip install azure-identity

ほしたら、あとは以下を使ってくださいませ。

ミソ:Responseの中に、language="ja"を書いておくことで日本語対応!

key = "YOURKEY"
endpoint = "YOURENDPOINT"

# key = "paste-your-key-here"
# endpoint = "paste-your-endpoint-here"

from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

# Authenticate the client using your key and endpoint 
def authenticate_client():
    ta_credential = AzureKeyCredential(key)
    text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint, 
            credential=ta_credential)
    return text_analytics_client

client = authenticate_client()

# Example function for detecting sentiment in text
def sentiment_analysis_example(client):

    documents = ["今日は人生で一番の日でした。君も僕と一緒に入れたらよかったのに。"]
    response = client.analyze_sentiment(documents=documents, language="ja")[0]
    print("Document Sentiment: {}".format(response.sentiment))
    print("Overall scores: positive={0:.2f}; neutral={1:.2f}; negative={2:.2f} \n".format(
        response.confidence_scores.positive,
        response.confidence_scores.neutral,
        response.confidence_scores.negative,
    ))
    for idx, sentence in enumerate(response.sentences):
        print("Sentence: {}".format(sentence.text))
        print("Sentence {} sentiment: {}".format(idx+1, sentence.sentiment))
        print("Sentence score:\nPositive={0:.2f}\nNeutral={1:.2f}\nNegative={2:.2f}\n".format(
            sentence.confidence_scores.positive,
            sentence.confidence_scores.neutral,
            sentence.confidence_scores.negative,
        ))
          
sentiment_analysis_example(client)

# Example method for detecting opinions in text 
def sentiment_analysis_with_opinion_mining_example(client):

    documents = [
        "飯とサービスがダメダメでした。でも、コンシェルジュは良かった。"
    ]

    result = client.analyze_sentiment(documents, show_opinion_mining=True, language="ja")
    doc_result = [doc for doc in result if not doc.is_error]

    positive_reviews = [doc for doc in doc_result if doc.sentiment == "positive"]
    negative_reviews = [doc for doc in doc_result if doc.sentiment == "negative"]

    positive_mined_opinions = []
    mixed_mined_opinions = []
    negative_mined_opinions = []

    for document in doc_result:
        print("Document Sentiment: {}".format(document.sentiment))
        print("Overall scores: positive={0:.2f}; neutral={1:.2f}; negative={2:.2f} \n".format(
            document.confidence_scores.positive,
            document.confidence_scores.neutral,
            document.confidence_scores.negative,
        ))
        for sentence in document.sentences:
            print("Sentence: {}".format(sentence.text))
            print("Sentence sentiment: {}".format(sentence.sentiment))
            print("Sentence score:\nPositive={0:.2f}\nNeutral={1:.2f}\nNegative={2:.2f}\n".format(
                sentence.confidence_scores.positive,
                sentence.confidence_scores.neutral,
                sentence.confidence_scores.negative,
            ))
            for mined_opinion in sentence.mined_opinions:
                target = mined_opinion.target
                print("......'{}' target '{}'".format(target.sentiment, target.text))
                print("......Target score:\n......Positive={0:.2f}\n......Negative={1:.2f}\n".format(
                    target.confidence_scores.positive,
                    target.confidence_scores.negative,
                ))
                for assessment in mined_opinion.assessments:
                    print("......'{}' assessment '{}'".format(assessment.sentiment, assessment.text))
                    print("......Assessment score:\n......Positive={0:.2f}\n......Negative={1:.2f}\n".format(
                        assessment.confidence_scores.positive,
                        assessment.confidence_scores.negative,
                    ))
            print("\n")
        print("\n")
          
sentiment_analysis_with_opinion_mining_example(client)

結果

Document Sentiment: positive
Overall scores: positive=0.77; neutral=0.22; negative=0.01

Sentence: 今日は人生で一番の日でした。
Sentence 1 sentiment: positive
Sentence score:
Positive=0.94
Neutral=0.05
Negative=0.01

Sentence: 君も僕と一緒に入れたらよかったのに。
Sentence 2 sentiment: positive
Sentence score:
Positive=0.60
Neutral=0.39
Negative=0.02


Document Sentiment: mixed
Overall scores: positive=0.49; neutral=0.00; negative=0.50

Sentence: 飯とサービスがダメダメでした。
Sentence sentiment: negative
Sentence score:
Positive=0.00
Neutral=0.00
Negative=1.00

--

Sentence: でも、コンシェルジュは良かった。
Sentence sentiment: positive
Sentence score:
Positive=0.99
Neutral=0.01
Negative=0.01

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?