现在我正在通过谷歌云库实现情感分析,我的代码是
string text = "Feeling Not Well";
var client = LanguageServiceClient.Create();
var response = client.AnalyzeSentiment(new Document()
{
Content = text,
Type = Document.Types.Type.PlainText
});
var sentiment = response.DocumentSentiment;
var Score = sentiment.Score;
var magnitude = sentiment.Magnitude;
但它给出了一个错误 var client = LanguageServiceClient.Create();. 错误是
应用程序默认凭据不可用。 如果在 Google Compute Engine 中运行,它们就可用。 否则,环境变量 GOOGLE_APPLICATION_CREDENTIALS 必须定义为指向定义凭据的文件。 参见 https://developers.google.com/accounts/docs/application-default-credentials获取更多信息。
请给我解决方案
最佳答案
你可以使用
gcloud auth application-default login
从命令行(假设您安装了 Cloud SDK),或生成并下载 service account JSON file然后将 GOOGLE_APPLICATION_CREDENTIALS
环境变量设置为指向该文件。
Create
方法调用将首先检查环境变量,如果未设置环境变量,然后从 gcloud
中查找应用程序默认凭据。
基本上,凭证选项是:
- 从服务帐户文件明确创建一个,例如
GoogleCredential.FromStream(stream)
并使用它创建一个Channel
,您可以将其传递给Create
,如 FAQ 中所述 - 在这种情况下调用不带任何参数(或传入 null)的创建:
- 如果您设置了
GOOGLE_APPLICATION_CREDENTIALS
环境变量,则假定这是服务帐户 JSON 文件所在的位置 - 否则,如果您运行了
gcloud auth application-default login
,将使用这些凭据 - 否则,如果您在 Google Cloud Platform(例如 Compute Engine 或 AppEngine Flexible)上运行,您将获得项目的默认凭据
- 否则调用失败
- 如果您设置了
此外,您可以使用 Document.FromPlainText
调用来简化您的代码:
string text = "Feeling Not Well";
var client = LanguageServiceClient.Create();
var response = client.AnalyzeSentiment(Document.FromPlainText(text));
var sentiment = response.DocumentSentiment;
var Score = sentiment.Score;
var magnitude = sentiment.Magnitude;
关于c# - 通过谷歌云库进行情感分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41407781/