您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:通过 Python 使用项目答案搜索Quickstart Project Answer Search with Python

下面的 Python 示例创建并发送“直布罗陀巨岩”相关信息的请求。The following Python example creates and sends a request for information about "Rock of Gibraltar".

先决条件Prerequisites

获取认知服务实验室免费试用版的访问密钥Get an access key for the free trial Cognitive Services Labs

本示例使用 Python 3.6.4This example uses Python 3.6.4

代码方案Code scenario

下面的代码创建一个 URL 预览。The following code creates a URL Preview. 它是通过以下步骤实现的:It is implemented in the following steps:

  1. 声明变量,以按主机和路径指定终结点。Declare variables to specify the endpoint by host and path.
  2. 指定要预览的查询 URL,然后添加查询参数。Specify the query URL to preview, and add the query parameter.
  3. 设置查询参数。Set the query parameter.
  4. 定义搜索函数,用以创建请求并添加 Ocp-Apim-Subscription-Key 标头 。Define the Search function that creates the request and adds the Ocp-Apim-Subscription-Key header.
  5. 设置 Ocp-Apim-Subscription-Key 标头 。Set the Ocp-Apim-Subscription-Key header.
  6. 建立连接,并发送请求。Make the connection, and send the request.
  7. 输出 JSON 结果。Print the JSON results.

本演示的完整代码如下:The complete code for this demo follows:

import http.client, urllib.parse
import json

# Replace the subscriptionKey string value with your valid subscription key.
subscriptionKey = 'YOUR-SUBSCRIPTION-KEY'

host = 'https://api.labs.cognitive.microsoft.com'
path = '/answerSearch/v7.0/search '

query = 'Rock of Gibraltar'

params = '?q=' + urllib.parse.quote (query) + '&mkt=en-us'

def get_local():
    headers = {'Ocp-Apim-Subscription-Key': subscriptionKey}
    conn = http.client.HTTPSConnection (host)
    conn.request ("GET", path + params, None, headers)
    response = conn.getresponse ()
    return response.read ()

result = get_local()
print (json.dumps(json.loads(result), indent=4))

后续步骤Next steps