Google Cloud Natural Language

用于调用 Google Cloud Natural Language gRPC API 以分析文本的情感、实体和内容的类型化接口。

简介

Google Cloud Natural Language 从文本中提取洞察,包括情感、实体和内容类别。该 gRPC API 通过 google.cloud.language.v1.LanguageService 服务公开,在 language.googleapis.com:443 上通过 TLS 访问,主要方法包括 AnalyzeSentimentAnalyzeEntitiesClassifyText

请求通过类型化类构建,例如 TsgcGRPCLanguageAnalyzeSentimentRequestTsgcGRPCLanguageAnalyzeEntitiesRequest,每个都携带一个 Document,其 DocType 设置为 PLAIN_TEXT,并连同要分析的文本内容。

下面的示例使用服务账户 JWT 进行身份验证,通过 TsgcHTTP2ClientTsgcGRPCClient 连接到 Natural Language 主机,设置授权 Bearer 元数据,并对一个纯文本句子调用 AnalyzeSentiment


    oHTTP2 := TsgcHTTP2Client.Create(nil);
    oHTTP2.Host := 'language.googleapis.com';
    oHTTP2.Port := 443;
    oHTTP2.TLS := True;

    oGRPC := TsgcGRPCClient.Create(nil);
    oGRPC.Client := oHTTP2;

    // service-account JWT authentication
    oGRPC.GoogleCloudOptions.JWT.KeyFile := 'service-account.json';
    oGRPC.GoogleCloudOptions.JWT.API_Endpoint := 'https://language.googleapis.com/';
    oGRPC.DefaultMetadata.AddValue('authorization', 'Bearer ' + oGRPC.GoogleCloudOptions.JWT.Token);

    // build the typed request and call the method
    oRequest := TsgcGRPCLanguageAnalyzeSentimentRequest.Create;
    try
      oRequest.Document.DocType := 'PLAIN_TEXT';
      oRequest.Document.Content := 'I really love this product, it works great!';
      oResponse := oGRPC.Call('google.cloud.language.v1.LanguageService', 'AnalyzeSentiment', oRequest.ToBytes);
      ShowMessage(oResponse.DataString);
    finally
      oRequest.Free;
    end;

方法

名称描述
AnalyzeSentiment分析文档的整体情感,返回分数和量级。
AnalyzeEntities检测文档中的命名实体(人物、地点、组织)。
ClassifyText将文档分类到各内容类别中。

演示

示例文件夹 Demos/21.GRPC/14.Natural_Language 中提供了一个可用的示例,演示如何使用 AnalyzeSentiment 方法进行身份验证并分析文本的情感。

另请参阅