GCP Natural Language APIで構文解析、感情分析を簡単実行
Natural Language APIの基本
https://cloud.google.com/natural-language/docs/basics
Example
前半は入門ガイドの例をそのまま。
後半は、文章を構文解析、トークン毎に感情分析実行。
事前準備
サービスアカウントを生成、ダウンロードして、環境変数に設定して下さい。
1 | GOOGLE_APPLICATION_CREDENTIALS="★ファイルパス★" |
Gradle
1 | compile 'com.google.cloud:google-cloud-language:1.99.0' |
Java Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import com.google.cloud.language.v1.Document; import com.google.cloud.language.v1.Document.Type; import com.google.cloud.language.v1.LanguageServiceClient; import com.google.cloud.language.v1.Sentiment; import com.google.cloud.language.v1.Token; import java.util.List; public class Main { public static void main(String[] args) { try (LanguageServiceClient language = LanguageServiceClient.create()) { String text = "素晴らしい天気だ。今日はどこかへ出かけよう。" ; Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).setLanguage( "ja" ).build(); Sentiment sentiment = language.analyzeSentiment(doc).getDocumentSentiment(); System.out.printf( "Text: %s%n" , text); System.out.printf( "Sentiment: %s, %s%n" , sentiment.getScore(), sentiment.getMagnitude()); List<Token> tokenList = language.analyzeSyntax(doc).getTokensList(); tokenList.forEach(token -> { System.out.println(token.getText().getContent()); Document tokenText = Document.newBuilder().setContent(token.getText().getContent()).setType(Type.PLAIN_TEXT).setLanguage( "ja" ).build(); Sentiment tokenSentiment = language.analyzeSentiment(tokenText).getDocumentSentiment(); System.out.println(tokenSentiment); }); } catch (Exception e) { } } } |
memo
- 「素晴らしい」
score:0.8
magnitude:0.8 - 「今日」
感情解析されない
感情分析の値の解釈は「Natural Language APIの基本」に記載されています。