Google的Cloud Natural Language API引发“请求包含无效参数”错误(400)

snr*_*vix 5 nlp google-apps-script sentiment-analysis

尝试在NLP API中使用documents.analyzeSentiment方法,但抛出错误,表明该参数无效。

出现的错误是这样的-

{错误= {代码= 400,消息=请求包含无效的参数。,状态= INVALID_ARGUMENT}}

这就是我在Apps脚本上尝试的内容-

function analyzeText() {

  var apiKey = 'MyAPIKeyViaCloudConsole'

  var text = "I love R&B music. Marvin Gaye is the best. 'What's Going On' is one of my favorite songs. It was so sad when Marvin Gaye died.";

  var requestUrl = 'https://language.googleapis.com/v1/documents:analyzeSentiment?key=' + apiKey;

  var data = {
    "document": {
      "language": "en",
      "content": text
    },
    "encodingType": "UTF8"
  };

  var options = {
    method : "POST",
    contentType: "application/json",
    payload : JSON.stringify(data),
    muteHttpExceptions: true
  };

  var response = UrlFetchApp.fetch(requestUrl, options);

  var data = JSON.parse(response);

  Logger.log(data);

}
Run Code Online (Sandbox Code Playgroud)

基本上,我打算对一堆东西(客户的评论,一些推文等)进行某种情感分析,一旦我的代码可以工作,我将分批处理这些事情。

我究竟做错了什么??:(

Sou*_*ria 6

看起来您将需要在数据参数中提供“类型”,而且我还将“语言”从plan en更新为en-us

尝试这个 -

function analyzeText() {

  var apiKey = 'YourAPIKey'

  var text = "Random Text as required";

  var requestUrl = 'https://language.googleapis.com/v1/documents:analyzeSentiment?key=' + apiKey;

  var data = {
    "document": {
      "language": "en-us",
      "type": "PLAIN_TEXT",
      "content": text
    },
    "encodingType": "UTF8"
  };

  var options = {
    method : "POST",
    contentType: "application/json",
    payload : JSON.stringify(data),
    muteHttpExceptions: true
  };

  var response = UrlFetchApp.fetch(requestUrl, options);

  var data = JSON.parse(response);

  Logger.log(data);

}
Run Code Online (Sandbox Code Playgroud)

显然,根据您的用例,您可能希望通过循环来迭代一批文本for

另外,请确保您的Google Cloud Console项目具有与其关联的结算帐户以运行Natural Language API。

  • @snrservix它记录在您提供的链接中... (2认同)