简体   繁体   English

C#Google API引发异常

[英]C# Google API throws exception

I am using Google API for the first time and I want to use Natural Language API. 我是第一次使用Google API,并且想使用自然语言API。 But I don't know how. 但是我不知道如何。

So I search the internet and found an example code. 因此,我在互联网上搜索并找到了示例代码。

But when it uses APIs, the program throws an exception. 但是,当使用API​​时,程序将引发异常。

problem source code and thrown exception: 有问题的源代码和引发的异常:

using Google.Cloud.Language.V1;
using System;

namespace GoogleCloudSamples
{
    public class QuickStart
    {
        public static void Main(string[] args)
        {
            // The text to analyze.
            string text = "Hello World!";
            try
            {
                var client = LanguageServiceClient.Create();
                var response = client.AnalyzeSentiment(new Document()
                {
                Content = text,
                Type = Document.Types.Type.PlainText
                });
                var sentiment = response.DocumentSentiment;
                Console.WriteLine($"Score: {sentiment.Score}");
                Console.WriteLine($"Magnitude: {sentiment.Magnitude}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

The console output: 控制台输出:

The Application Default Credentials are not available.
They are available if running on Google Compute Engine.
Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials.
See https://developers.google.com/accounts/docs/application-default-credentials for more information.

What should I do? 我该怎么办?

I had used NLP a year ago for entity analysis. 我一年前曾使用NLP进行实体分析。 I had used Google.Apis.CloudNaturalLanguage.v1 . 我曾经使用过Google.Apis.CloudNaturalLanguage.v1 I put together my code with what you have written for sentiment analysis. 我将代码与您编写的用于情感分析的代码放在一起。 You will need the API key for this: 您将需要以下API密钥:

var service = new CloudNaturalLanguageService(new CloudNaturalLanguageService.Initializer { ApiKey = ApiKey });

var req = new AnalyzeSentimentRequest {
    Document = new Document()
    {
        Content = text,
        Type = Document.Types.Type.PlainText
    },
    EncodingType = "UTF8"
};

var output = service.Documents.AnalyzeSentiment(req);
var exe = output.Execute();

Hope this works. 希望这行得通。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM