快速入门:使用 Node.js 调用文本分析认知服务Quickstart: Use Node.js to call the Text Analytics Cognitive Service

本文展示了如何将 文本分析 API 与 Node.JS 配合使用来检测语言分析情绪提取关键短语以及识别链接的实体This article shows you how to detect language, analyze sentiment, extract key phrases, and identify linked entities using the Text Analytics APIs with Node.JS.

提示

若要获取详细的 API 技术文档并查看其如何发挥作用,请使用以下链接。For detailed API technical documentation and to see it in action, use the following links. 还可以从内置 API 测试控制台发送 POST 请求。You can also send POST requests from the built-in API test console. 无需进行任何设置,只需将资源键和 JSON 文档粘贴到请求中:No setup is required, simply paste your resource key and JSON documents into the request:

先决条件Prerequisites

必须拥有可以访问文本分析 API 的认知服务 API 订阅You must have a Cognitive Services API subscription with access to the Text Analytics API. 如果没有订阅,可以创建一个 1 元试用帐户If you don't have a subscription, you can create a 1rmb trial account. 在继续操作之前,需使用激活帐户后由系统提供的文本分析订阅密钥。Before continuing, you will need the Text Analytics subscription key provided after activating your account.

检测语言Detect language

语言检测 API 使用检测语言方法检测文本文档的语言。The Language Detection API detects the language of a text document, using the Detect Language method.

  1. 在最喜爱的 IDE 或桌面上的某个文件夹中创建一个新的 Node.JS 项目。Create a new Node.JS project in your favorite IDE or a folder on your desktop.
  2. 将下面提供的代码添加到新的 .js 文件中。Add the code provided below to a new .js file.
  3. 将密钥和终结点复制到代码中。Copy your key and endpoint into the code.
  4. 从 IDE 或命令行运行该程序,例如 npm startnode detect.jsRun the program from your IDE or command line, for example npm start or node detect.js.
'use strict';

let https = require ('https');
subscription_key = "<paste-your-text-analytics-key-here>";
endpoint = "<paste-your-text-analytics-endpoint-here>";

let path = '/text/analytics/v3.0/languages';

let response_handler = function (response) {
    let body = '';
    response.on('data', function (d) {
        body += d;
    });
    response.on('end', function () {
        let body_ = JSON.parse(body);
        let body__ = JSON.stringify(body_, null, '  ');
        console.log(body__);
    });
    response.on('error', function (e) {
        console.log('Error: ' + e.message);
    });
};

let get_language = function (documents) {
    let body = JSON.stringify(documents);

    let request_params = {
        method: 'POST',
        hostname: (new URL(endpoint)).hostname,
        path: path,
        headers: {
            'Ocp-Apim-Subscription-Key': subscription_key,
        }
    };

    let req = https.request(request_params, response_handler);
    req.write(body);
    req.end();
}

let documents = {
    'documents': [
        { 'id': '1', 'text': 'This is a document written in English.' },
        { 'id': '2', 'text': 'Este es un document escrito en Español.' },
        { 'id': '3', 'text': '这是一个用中文写的文件' }
    ]
};

get_language(documents);

语言检测响应Language detection response

在 JSON 中返回成功的响应,如以下示例所示:A successful response is returned in JSON, as shown in the following example:

{
    "documents": [
        {
            "id": "1",
            "detectedLanguage": {
                "name": "English",
                "iso6391Name": "en",
                "confidenceScore": 1.0
            },
            "warnings": []
        },
        {
            "id": "2",
            "detectedLanguage": {
                "name": "Spanish",
                "iso6391Name": "es",
                "confidenceScore": 1.0
            },
            "warnings": []
        },
        {
            "id": "3",
            "detectedLanguage": {
                "name": "Chinese_Simplified",
                "iso6391Name": "zh_chs",
                "confidenceScore": 1.0
            },
            "warnings": []
        }
    ],
    "errors": [],
    "modelVersion": "2019-10-01"
}

分析情绪Analyze sentiment

情绪分析 API 使用 Sentiment 方法检测一组文本记录的情绪。The Sentiment Analysis API detects the sentiment of a set of text records, using the Sentiment method. 通过在原始文本中分析有关积极和消极情绪的线索,可以使用情绪分析确定客户如何看待你的品牌或主题。Sentiment analysis can be used to find out what customers think of your brand or topic by analyzing raw text for clues about positive or negative sentiment. 以下示例提供了两个文档的分数,一个是英文文档,另一个是西班牙文文档。The following example provides scores for two documents, one in English and another in Spanish.

  1. 在最喜爱的 IDE 或桌面上的某个文件夹中创建一个新的 Node.JS 项目。Create a new Node.JS project in your favorite IDE or a folder on your desktop.
  2. 将下面提供的代码添加到新的 .js 文件中。Add the code provided below to a new .js file.
  3. 将文本分析密钥和终结点复制到代码中。Copy your Text Analytics key and endpoint into the code.
  4. 从 IDE 或命令行运行该程序,例如 npm startnode sentiment.jsRun the program from your IDE or command line, for example npm start or node sentiment.js.
'use strict';

let https = require ('https');

subscription_key = "<paste-your-text-analytics-key-here>";
endpoint = "<paste-your-text-analytics-endpoint-here>";

let path = '/text/analytics/v3.0/sentiment';

let response_handler = function (response) {
    let body = '';
    response.on('data', function (d) {
        body += d;
    });
    response.on('end', function () {
        let body_ = JSON.parse(body);
        let body__ = JSON.stringify(body_, null, '  ');
        console.log(body__);
    });
    response.on('error', function (e) {
        console.log('Error: ' + e.message);
    });
};

let get_sentiments = function (documents) {
    let body = JSON.stringify(documents);

    let request_params = {
        method: 'POST',
        hostname: (new URL(endpoint)).hostname,
        path: path,
        headers: {
            'Ocp-Apim-Subscription-Key': subscription_key,
        }
    };

    let req = https.request(request_params, response_handler);
    req.write(body);
    req.end();
}

let documents = {
    'documents': [
        { 'id': '1', 'language': 'en', 'text': 'I really enjoy the new XBox One S. It has a clean look, it has 4K/HDR resolution and it is affordable.' },
        { 'id': '2', 'language': 'es', 'text': 'Este ha sido un dia terrible, llegué tarde al trabajo debido a un accidente automobilistico.' },
    ]
};

get_sentiments(documents);

情绪分析响应Sentiment analysis response

如果得分接近 1.0,则测量结果为积极;如果得分接近 0.0,则测量结果为消极。The result is measured as positive if it's scored closer to 1.0 and negative if it's scored closer to 0.0. 在 JSON 中返回成功的响应,如以下示例所示:A successful response is returned in JSON, as shown in the following example:

{
    "documents": [
        {
            "id": "1",
            "sentiment": "positive",
            "confidenceScores": {
                "positive": 1.0,
                "neutral": 0.0,
                "negative": 0.0
            },
            "sentences": [
                {
                    "sentiment": "positive",
                    "confidenceScores": {
                        "positive": 1.0,
                        "neutral": 0.0,
                        "negative": 0.0
                    },
                    "offset": 0,
                    "length": 102,
                    "text": "I really enjoy the new XBox One S. It has a clean look, it has 4K/HDR resolution and it is affordable."
                }
            ],
            "warnings": []
        },
        {
            "id": "2",
            "sentiment": "negative",
            "confidenceScores": {
                "positive": 0.02,
                "neutral": 0.05,
                "negative": 0.93
            },
            "sentences": [
                {
                    "sentiment": "negative",
                    "confidenceScores": {
                        "positive": 0.02,
                        "neutral": 0.05,
                        "negative": 0.93
                    },
                    "offset": 0,
                    "length": 92,
                    "text": "Este ha sido un dia terrible, llegué tarde al trabajo debido a un accidente automobilistico."
                }
            ],
            "warnings": []
        }
    ],
    "errors": [],
    "modelVersion": "2020-04-01"
}

提取关键短语Extract key phrases

关键短语提取 API 使用关键短语方法从文本文档中提取关键短语。The Key Phrase Extraction API extracts key-phrases from a text document, using the Key Phrases method. 关键短语提取用于快速识别文档或文本的要点。Key phrase extraction is used to quickly identify the main points of a document or text. 以下示例为英文和西班牙文文档提取关键短语。The following example extracts key phrases for both English and Spanish documents.

  1. 在最喜爱的 IDE 或桌面上的某个文件夹中创建一个新的 Node.JS 项目。Create a new Node.JS project in your favorite IDE or a folder on your desktop.
  2. 将下面提供的代码添加到新的 .js 文件中。Add the code provided below to a new .js file.
  3. 将文本分析密钥和终结点复制到代码中。Copy your Text Analytics key and endpoint into the code.
  4. 从 IDE 或命令行运行该程序,例如 npm startnode key-phrases.jsRun the program from your IDE or command line, for example npm start or node key-phrases.js.
'use strict';

let https = require ('https');

subscription_key = "<paste-your-text-analytics-key-here>";
endpoint = "<paste-your-text-analytics-endpoint-here>";

let path = '/text/analytics/v3.0/keyPhrases';

let response_handler = function (response) {
    let body = '';
    response.on('data', function (d) {
        body += d;
    });
    response.on('end', function () {
        let body_ = JSON.parse(body);
        let body__ = JSON.stringify(body_, null, '  ');
        console.log(body__);
    });
    response.on('error', function (e) {
        console.log('Error: ' + e.message);
    });
};

let get_key_phrases = function (documents) {
    let body = JSON.stringify(documents);

    let request_params = {
        method: 'POST',
        hostname: (new URL(endpoint)).hostname,
        path: path,
        headers: {
            'Ocp-Apim-Subscription-Key': subscription_key,
        }
    };

    let req = https.request(request_params, response_handler);
    req.write(body);
    req.end();
}

let documents = {
    'documents': [
        { 'id': '1', 'language': 'en', 'text': 'I really enjoy the new XBox One S. It has a clean look, it has 4K/HDR resolution and it is affordable.' },
        { 'id': '2', 'language': 'es', 'text': 'Si usted quiere comunicarse con Carlos, usted debe de llamarlo a su telefono movil. Carlos es muy responsable, pero necesita recibir una notificacion si hay algun problema.' },
        { 'id': '3', 'language': 'en', 'text': 'The Grand Hotel is a new hotel in the center of Seattle. It earned 5 stars in my review, and has the classiest decor I\'ve ever seen.' }
    ]
};

get_key_phrases(documents);

关键短语提取响应Key phrase extraction response

在 JSON 中返回成功的响应,如以下示例所示:A successful response is returned in JSON, as shown in the following example:

{
    "documents": [
        {
            "id": "1",
            "keyPhrases": [
                "HDR resolution",
                "new XBox",
                "clean look"
            ],
            "warnings": []
        },
        {
            "id": "2",
            "keyPhrases": [
                "Carlos",
                "notificacion",
                "algun problema",
                "telefono movil"
            ],
            "warnings": []
        },
        {
            "id": "3",
            "keyPhrases": [
                "new hotel",
                "Grand Hotel",
                "review",
                "center of Seattle",
                "classiest decor",
                "stars"
            ],
            "warnings": []
        }
    ],
    "errors": [],
    "modelVersion": "2019-10-01"
}

识别链接实体Identify linked entities

实体 API 使用实体方法识别文本文档中的已知实体。The Entities API identifies well-known entities in a text document, using the Entities method. 实体从文本中提取字词,如“United States”,然后提供此词语的类型和/或维基百科的链接。Entities extract words from text, like "United States", then give you the type and/or Wikipedia link for this word(s). “United States”的类型为 location,而在维基百科上的链接为 https://en.wikipedia.org/wiki/United_StatesThe type for "United States" is location, while the link to Wikipedia is https://en.wikipedia.org/wiki/United_States. 以下示例识别英文文档的实体。The following example identifies entities for English documents.

  1. 在最喜爱的 IDE 或桌面上的某个文件夹中创建一个新的 Node.JS 项目。Create a new Node.JS project in your favorite IDE or a folder on your desktop.
  2. 将下面提供的代码添加到新的 .js 文件中。Add the code provided below to a new .js file.
  3. 将文本分析密钥和终结点复制到代码中Copy your Text analytics key and endpoint into the code
  4. 从 IDE 或命令行运行该程序,例如 npm startnode entities.jsRun the program from your IDE or command line, for example npm start or node entities.js.
'use strict';

let https = require ('https');

subscription_key = "<paste-your-text-analytics-key-here>";
endpoint = "<paste-your-text-analytics-endpoint-here>";

let path = '/text/analytics/v3.0/entities/recognition/general';

let response_handler = function (response) {
    let body = '';
    response.on('data', function (d) {
        body += d;
    });
    response.on('end', function () {
        let body_ = JSON.parse(body);
        let body__ = JSON.stringify(body_, null, '  ');
        console.log(body__);
    });
    response.on('error', function (e) {
        console.log('Error: ' + e.message);
    });
};

let get_entities = function (documents) {
    let body = JSON.stringify(documents);

    let request_params = {
        method: 'POST',
        hostname: (new URL(endpoint)).hostname,
        path: path,
        headers: {
            'Ocp-Apim-Subscription-Key': subscription_key,
        }
    };

    let req = https.request(request_params, response_handler);
    req.write(body);
    req.end();
}

let documents = {
    'documents': [
        { 'id': '1', 'language': 'en', 'text': 'Microsoft is an It company.' }
    ]
};

get_entities(documents);

实体提取响应Entity extraction response

在 JSON 中返回成功的响应,如以下示例所示:A successful response is returned in JSON, as shown in the following example:

{
    "documents": [
        {
            "id": "1",
            "entities": [
                {
                    "text": "Microsoft",
                    "category": "Organization",
                    "offset": 0,
                    "length": 9,
                    "confidenceScore": 0.86
                },
                {
                    "text": "IT",
                    "category": "Skill",
                    "offset": 16,
                    "length": 2,
                    "confidenceScore": 0.8
                }
            ],
            "warnings": []
        }
    ],
    "errors": [],
    "modelVersion": "2020-04-01"
}

后续步骤Next steps

另请参阅See also

文本分析概述Text Analytics overview
常见问题解答 (FAQ)Frequently asked questions (FAQ)