你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 JavaScript 的 Azure 文本分析 客户端库 - 版本 5.1.0

Azure TextAnalytics 是一项基于云的服务,提供对原始文本的高级自然语言处理,包括六个主要功能:

注意:此 SDK 面向 Azure 文本分析 服务 API 版本 3.1.0。

  • 语言检测
  • 情绪分析
  • 关键短语提取
  • 命名实体识别
  • 识别个人身份信息
  • 链接实体识别
  • 医疗保健分析
  • 支持每个文档的多个操作

使用客户端库可以执行以下操作:

  • 检测写入的语言输入文本。
  • 通过分析原始文本以获取有关正面或负面情绪的线索,确定客户对你品牌或主题的看法。
  • 自动提取关键短语,以快速识别要点。
  • 识别文本中的实体并将其分类为人员、地点、组织、日期/时间、数量、百分比、货币、医疗保健特定等。
  • 一次执行多个上述任务。

关键链接:

入门

目前支持的环境

有关更多详细信息,请参阅我们的支持政策

先决条件

如果使用 Azure CLI,请将 和 <your-resource-name> 替换为<your-resource-group-name>自己的唯一名称:

az cognitiveservices account create --kind TextAnalytics --resource-group <your-resource-group-name> --name <your-resource-name> --sku <your-sku-name> --location <your-location>

安装 @azure/ai-text-analytics

使用 npm安装适用于 JavaScript 的 Azure 文本分析 客户端库:

npm install @azure/ai-text-analytics

创建 TextAnalyticsClient 并对其进行身份验证

若要创建客户端对象以访问 文本分析 API,需要endpoint文本分析资源的 和 credential。 文本分析客户端可以使用 Azure Active Directory 凭据或 API 密钥凭据进行身份验证。

可以在 Azure 门户中 或使用以下 Azure CLI 代码片段找到文本分析资源的终结点:

az cognitiveservices account show --name <your-resource-name> --resource-group <your-resource-group-name> --query "endpoint"

使用 API 密钥

使用 Azure 门户浏览到文本分析资源并检索 API 密钥,或使用下面的 Azure CLI 代码片段:

注意: 有时,API 密钥称为“订阅密钥”或“订阅 API 密钥”。

az cognitiveservices account keys list --resource-group <your-resource-group-name> --name <your-resource-name>

拥有 API 密钥和终结点后,可以使用 AzureKeyCredential 类对客户端进行身份验证,如下所示:

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

使用 Azure Active Directory 凭据

大多数示例中都使用客户端 API 密钥身份验证,但也可以使用 Azure 标识库通过 Azure Active Directory 进行身份验证。 若要使用如下所示的 DefaultAzureCredential 提供程序或 Azure SDK 提供的其他凭据提供程序,请安装包 @azure/identity

npm install @azure/identity

还需要注册新的 AAD 应用程序,并通过将角色分配给"Cognitive Services User"服务主体来授予对文本分析的访问权限 (注意:其他角色(如 )"Owner"不会授予必要的权限,仅"Cognitive Services User"足以) 运行示例和示例代码。

将 AAD 应用程序的客户端 ID、租户 ID 和客户端密码的值设置为环境变量:AZURE_CLIENT_ID、、AZURE_TENANT_IDAZURE_CLIENT_SECRET

const { TextAnalyticsClient } = require("@azure/ai-text-analytics");
const { DefaultAzureCredential } = require("@azure/identity");

const client = new TextAnalyticsClient("<endpoint>", new DefaultAzureCredential());

关键概念

TextAnalyticsClient

TextAnalyticsClient是使用 文本分析 客户端库的开发人员的主要接口。 浏览此客户端对象上的方法,以了解可以访问的 文本分析 服务的不同功能。

输入

文档表示要由文本分析服务中的预测模型分析的单个输入单位。 对 TextAnalyticsClient 的操作采用要作为批处理分析的输入集合。 操作方法具有重载,允许将输入表示为字符串或具有附加元数据的对象。

例如,每个文档都可以作为数组中的字符串传递,例如

const documents = [
  "I hated the movie. It was so slow!",
  "The movie made it into my top ten favorites.",
  "What a great movie!"
];

或者,如果要传入按项的文档idlanguagecountryHint/,则可以将其作为 或 DetectLanguageInput 列表TextDocumentInput提供,具体取决于操作;

const textDocumentInputs = [
  { id: "1", language: "en", text: "I hated the movie. It was so slow!" },
  { id: "2", language: "en", text: "The movie made it into my top ten favorites." },
  { id: "3", language: "en", text: "What a great movie!" }
];

请参阅输入 的服务限制 ,包括文档长度限制、最大批大小和支持的文本编码。

返回值

对应于单个文档的返回值是成功结果或错误对象。 每个方法返回 TextAnalyticsClient 一个异类数组,其中包含对应于按索引的输入的结果和错误。 文本输入及其结果在输入和结果集合中具有相同的索引。 该集合还可以选择性地包含有关输入批处理的信息以及字段中的处理 statistics 方式。

结果(如 AnalyzeSentimentResult)是文本分析操作的结果,其中包含有关单个文本输入的预测。 操作的结果类型还可以选择性地包含有关输入文档及其处理方式的信息。

错误对象 TextAnalyticsErrorResult指示服务在处理文档时遇到错误,并包含有关错误的信息。

文档错误处理

在操作返回的集合中,错误与成功响应的区别是存在 error 属性,如果遇到错误,该属性包含内部 TextAnalyticsError 对象。 对于成功的结果对象,此属性 始终undefined为 。

例如,若要筛选出所有错误,可以使用以下 filter

const results = await client.analyzeSentiment(documents);
const onlySuccessful = results.filter((result) => result.error === undefined);

注意:如果在配置中tsconfig.json将 设置为 true ,TypeScript compilerOptions.strictNullChecks 用户可以受益于结果和错误对象的更好类型检查。 例如:

const [result] = await client.analyzeSentiment(["Hello world!"]);

if (result.error !== undefined) {
  // In this if block, TypeScript will be sure that the type of `result` is
  // `TextAnalyticsError` if compilerOptions.strictNullChecks is enabled in
  // the tsconfig.json

  console.log(result.error);
}

此功能是在 TypeScript 3.2 中引入的,因此 TypeScript 3.1 的用户必须将结果值强制转换为其相应的成功变体,如下所示:

const [result] = await client.detectLanguage(["Hello world!"]);

if (result.error === undefined) {
  const { primaryLanguage } = result as DetectLanguageSuccessResult;
}

示例

分析情绪

分析文本的情绪,以确定它是正面的、消极的、中性的还是混合的,包括每句话的情绪分析和置信度分数。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "I did not like the restaurant. The food was too spicy.",
  "The restaurant was decorated beautifully. The atmosphere was unlike any other restaurant I've been to.",
  "The food was yummy. :)"
];

async function main() {
  const results = await client.analyzeSentiment(documents);

  for (const result of results) {
    if (result.error === undefined) {
      console.log("Overall sentiment:", result.sentiment);
      console.log("Scores:", result.confidenceScores);
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}

main();

若要获取与产品/服务方面(也称为自然语言处理 (NLP) 中基于方面的情绪分析)相关的更精细的信息,请参阅 此处关于使用观点挖掘进行情绪分析的示例。

识别实体

识别文本中的实体并将其分类为人员、地点、组织、日期/时间、数量、货币等。

language 参数是可选的。 如果未指定,将使用默认的英语模型。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Microsoft was founded by Bill Gates and Paul Allen.",
  "Redmond is a city in King County, Washington, United States, located 15 miles east of Seattle.",
  "Jeff bought three dozen eggs because there was a 50% discount."
];

async function main() {
  const results = await client.recognizeEntities(documents, "en");

  for (const result of results) {
    if (result.error === undefined) {
      console.log(" -- Recognized entities for input", result.id, "--");
      for (const entity of result.entities) {
        console.log(entity.text, ":", entity.category, "(Score:", entity.confidenceScore, ")");
      }
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}

main();

识别 PII 实体

有一个单独的终结点和操作用于识别个人身份信息 (PII) 文本,如社会安全号码、银行帐户信息、信用卡号等。其用法与上述标准实体识别非常相似:

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");
const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));
const documents = [
  "The employee's SSN is 555-55-5555.",
  "The employee's phone number is (555) 555-5555."
];
async function main() {
  const results = await client.recognizePiiEntities(documents, "en");
  for (const result of results) {
    if (result.error === undefined) {
      console.log(" -- Recognized PII entities for input", result.id, "--");
      for (const entity of result.entities) {
        console.log(entity.text, ":", entity.category, "(Score:", entity.confidenceScore, ")");
      }
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}
main();

识别链接实体

“链接”实体是存在于维基百科) 等知识库 (中的实体。 该recognizeLinkedEntities操作可以消除实体的歧义,方法是确定实体在知识库中可能引用的条目 (例如,在一段文本中,“火星”一词是否是指行星,或罗马战神) 。 链接实体包含指向提供实体定义的知识库的关联 URL。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Microsoft was founded by Bill Gates and Paul Allen.",
  "Easter Island, a Chilean territory, is a remote volcanic island in Polynesia.",
  "I use Azure Functions to develop my product."
];

async function main() {
  const results = await client.recognizeLinkedEntities(documents, "en");

  for (const result of results) {
    if (result.error === undefined) {
      console.log(" -- Recognized linked entities for input", result.id, "--");
      for (const entity of result.entities) {
        console.log(entity.name, "(URL:", entity.url, ", Source:", entity.dataSource, ")");
        for (const match of entity.matches) {
          console.log(
            "  Occurrence:",
            '"' + match.text + '"',
            "(Score:",
            match.confidenceScore,
            ")"
          );
        }
      }
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}

main();

提取关键短语

关键短语提取标识文档中的主要谈话点。 例如,给定输入文本“The food was delicious and there were wonderful staff”,服务会返回“food”和“wonderful staff”。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Redmond is a city in King County, Washington, United States, located 15 miles east of Seattle.",
  "I need to take my cat to the veterinarian.",
  "I will travel to South America in the summer."
];

async function main() {
  const results = await client.extractKeyPhrases(documents, "en");

  for (const result of results) {
    if (result.error === undefined) {
      console.log(" -- Extracted key phrases for input", result.id, "--");
      console.log(result.keyPhrases);
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}

main();

检测语言

确定一段文本的语言。

参数 countryHint 是可选的,但如果知道原产国,则可以帮助服务提供正确的输出。 如果提供,则应将其设置为 ISO-3166 Alpha-2 双字母国家/地区代码 (,例如美国的“us”或“jp”(日本) 或值 "none")。 如果未提供 参数,则将使用默认"us" (美国) 模型。 如果不知道文档的原产国,则应使用 参数"none",文本分析服务将应用针对未知来源国家/地区优化的模型。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "This is written in English.",
  "Il documento scritto in italiano.",
  "Dies ist in deutscher Sprache verfasst."
];

async function main() {
  const results = await client.detectLanguage(documents, "none");

  for (const result of results) {
    if (result.error === undefined) {
      const { primaryLanguage } = result;
      console.log(
        "Input #",
        result.id,
        "identified as",
        primaryLanguage.name,
        "( ISO6391:",
        primaryLanguage.iso6391Name,
        ", Score:",
        primaryLanguage.confidenceScore,
        ")"
      );
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}

main();

分析医疗保健实体

医疗保健分析可识别医疗保健实体。 例如,给定输入文本“规定的 100mg 布洛芬,每天服用两次”,服务返回“100mg”,分类为剂量,“布洛芬”为药物名称,“每日两次”作为频率。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Prescribed 100mg ibuprofen, taken twice daily.",
  "Patient does not suffer from high blood pressure."
];

async function main() {
  const poller = await client.beginAnalyzeHealthcareEntities(documents);
  const results = await poller.pollUntilDone();

  for await (const result of results) {
    console.log(`- Document ${result.id}`);
    if (!result.error) {
      console.log("\tRecognized Entities:");
      for (const entity of result.entities) {
        console.log(`\t- Entity ${entity.text} of type ${entity.category}`);
      }
    } else console.error("\tError:", result.error);
  }
}

main();

分析操作

分析操作允许同时应用多个分析 (命名操作) 。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Microsoft was founded by Bill Gates and Paul Allen.",
  "The employee's SSN is 555-55-5555.",
  "Easter Island, a Chilean territory, is a remote volcanic island in Polynesia.",
  "I use Azure Functions to develop my product."
];

async function main() {
  const actions = {
    recognizeEntitiesActions: [{ modelVersion: "latest" }],
    recognizePiiEntitiesActions: [{ modelVersion: "latest" }],
    extractKeyPhrasesActions: [{ modelVersion: "latest" }]
  };
  const poller = await client.beginAnalyzeActions(documents, actions);
  const resultPages = await poller.pollUntilDone();
  for await (const page of resultPages) {
    const keyPhrasesAction = page.extractKeyPhrasesResults[0];
    if (!keyPhrasesAction.error) {
      for (const doc of keyPhrasesAction.results) {
        console.log(`- Document ${doc.id}`);
        if (!doc.error) {
          console.log("\tKey phrases:");
          for (const phrase of doc.keyPhrases) {
            console.log(`\t- ${phrase}`);
          }
        } else {
          console.error("\tError:", doc.error);
        }
      }
    }

    const entitiesAction = page.recognizeEntitiesResults[0];
    if (!entitiesAction.error) {
      for (const doc of entitiesAction.results) {
        console.log(`- Document ${doc.id}`);
        if (!doc.error) {
          console.log("\tEntities:");
          for (const entity of doc.entities) {
            console.log(`\t- Entity ${entity.text} of type ${entity.category}`);
          }
        } else {
          console.error("\tError:", doc.error);
        }
      }
    }

    const piiEntitiesAction = page.recognizePiiEntitiesResults[0];
    if (!piiEntitiesAction.error) {
      for (const doc of piiEntitiesAction.results) {
        console.log(`- Document ${doc.id}`);
        if (!doc.error) {
          console.log("\tPii Entities:");
          for (const entity of doc.entities) {
            console.log(`\t- Entity ${entity.text} of type ${entity.category}`);
          }
        } else {
          console.error("\tError:", doc.error);
        }
      }
    }
  }
}

main();

疑难解答

日志记录

启用日志记录可能有助于发现有关故障的有用信息。 若要查看 HTTP 请求和响应的日志,请将 AZURE_LOG_LEVEL 环境变量设置为 info。 或者,可以在运行时通过调用 @azure/logger 中的 setLogLevel 来启用日志记录:

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

有关如何启用日志的更详细说明,请查看 @azure/logger 包文档

后续步骤

请查看 示例 目录,获取有关如何使用此库的详细示例。

贡献

若要为此库做出贡献,请阅读贡献指南,详细了解如何生成和测试代码。

曝光数