|
| 1 | +// Copyright 2016 Google Inc. All rights reserved. |
| 2 | +// Use of this source code is governed by the Apache 2.0 |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +// [START language_quickstart] |
| 6 | +// Sample language_quickstart uses the Google Cloud Natural API to analyze the |
| 7 | +// sentiment of "Hello, world!". |
| 8 | +package main |
| 9 | + |
| 10 | +import ( |
| 11 | + "fmt" |
| 12 | + "golang.org/x/net/context" |
| 13 | + "log" |
| 14 | + |
| 15 | + // Imports the Google Cloud Natural Language API client package |
| 16 | + language "cloud.google.com/go/language/apiv1" |
| 17 | + languagepb "google.golang.org/genproto/googleapis/cloud/language/v1" |
| 18 | +) |
| 19 | + |
| 20 | +func main() { |
| 21 | + ctx := context.Background() |
| 22 | + |
| 23 | + // Creates a client |
| 24 | + client, err := language.NewClient(ctx) |
| 25 | + if err != nil { |
| 26 | + log.Fatalf("Failed to create client: %v", err) |
| 27 | + } |
| 28 | + |
| 29 | + // The text to analyze |
| 30 | + text := "Hello, world!" |
| 31 | + |
| 32 | + // Detects the sentiment of the text |
| 33 | + sentiment, err := client.AnalyzeSentiment(ctx, &languagepb.AnalyzeSentimentRequest{ |
| 34 | + Document: &languagepb.Document{ |
| 35 | + Source: &languagepb.Document_Content{ |
| 36 | + Content: text, |
| 37 | + }, |
| 38 | + Type: languagepb.Document_PLAIN_TEXT, |
| 39 | + }, |
| 40 | + EncodingType: languagepb.EncodingType_UTF8, |
| 41 | + }) |
| 42 | + if err != nil { |
| 43 | + log.Fatalf("Failed to analyze text: %v", err) |
| 44 | + } |
| 45 | + |
| 46 | + fmt.Printf("Text: %v\n", text) |
| 47 | + if sentiment.DocumentSentiment.Score >= 0 { |
| 48 | + fmt.Printf("Sentiment: positive") |
| 49 | + } else { |
| 50 | + fmt.Printf("Sentiment: negative") |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +// [END language_quickstart] |
0 commit comments