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

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

提示

若要获取详细的 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 中新建一个 Ruby 项目。Create a new Ruby project in your favorite IDE.
  2. 添加以下提供的代码。Add the code provided below.
  3. 将文本分析密钥和终结点复制到代码中。Copy your Text Analytics key and endpoint into the code.
  4. 运行该程序。Run the program.
# encoding: UTF-8

require 'net/https'
require 'uri'
require 'json'

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

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

uri = URI(endpoint + path)

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' => '这是一个用中文写的文件' }
]}

puts 'Please wait a moment for the results to appear.'

request = Net::HTTP::Post.new(uri)
request['Content-Type'] = "application/json"
request['Ocp-Apim-Subscription-Key'] = subscription_key
request.body = documents.to_json

response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    http.request (request)
end

puts JSON::pretty_generate (JSON (response.body))

语言检测响应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. 以下示例为两个文档打分,一个是英文文档,另一个是西班牙文文档。The following example scores two documents, one in English and another in Spanish.

  1. 在你喜欢使用的 IDE 中新建一个 Ruby 项目。Create a new Ruby project in your favorite IDE.
  2. 添加以下提供的代码。Add the code provided below.
  3. 将文本分析密钥和终结点复制到代码中。Copy your Text Analytics key and endpoint into the code.
  4. 运行该程序。Run the program.
# encoding: UTF-8

require 'net/https'
require 'uri'
require 'json'

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

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

uri = URI(endpoint + path)

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.' }
]}

puts 'Please wait a moment for the results to appear.'

request = Net::HTTP::Post.new(uri)
request['Content-Type'] = "application/json"
request['Ocp-Apim-Subscription-Key'] = subscription_key
request.body = documents.to_json

response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    http.request (request)
end

puts JSON::pretty_generate (JSON (response.body))

情绪分析响应Sentiment analysis response

在 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. 以下示例为英文和西班牙文文档提取关键短语。The following example extracts key phrases for both English and Spanish documents.

  1. 在你喜欢使用的 IDE 中新建一个 Ruby 项目。Create a new Ruby project in your favorite IDE.
  2. 添加以下提供的代码。Add the code provided below.
  3. 将文本分析密钥和终结点复制到代码中。Copy your Text Analytics key and endpoint into the code.
  4. 运行该程序。Run the program.
# encoding: UTF-8

require 'net/https'
require 'uri'
require 'json'

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

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

uri = URI(endpoint + path)

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.' },
]}

puts 'Please wait a moment for the results to appear.'

request = Net::HTTP::Post.new(uri)
request['Content-Type'] = "application/json"
request['Ocp-Apim-Subscription-Key'] = subscription_key
request.body = documents.to_json

response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    http.request (request)
end

puts JSON::pretty_generate (JSON (response.body))

关键短语提取响应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"
}

实体识别Entity recognition

实体 API 使用实体方法提取文本文档中的实体。The Entities API extracts entities in a text document, using the Entities method. 以下示例识别英文文档的实体。The following example identifies entities for English documents.

  1. 在你喜欢使用的 IDE 中新建一个 Ruby 项目。Create a new Ruby project in your favorite IDE.
  2. 添加以下提供的代码。Add the code provided below.
  3. 将文本分析密钥和终结点复制到代码中。Copy your Text Analytics key and endpoint into the code.
  4. 运行该程序。Run the program.
# encoding: UTF-8

require 'net/https'
require 'uri'
require 'json'

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

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

uri = URI(endpoint + path)

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

puts 'Please wait a moment for the results to appear.'

request = Net::HTTP::Post.new(uri)
request['Content-Type'] = "application/json"
request['Ocp-Apim-Subscription-Key'] = subscription_key
request.body = documents.to_json

response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    http.request (request)
end

puts JSON::pretty_generate (JSON (response.body))

实体提取响应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)