可以通过调用Bing Search API(v7)中的“q”查询参数来获取特色片段。以下是使用Bing搜索API(v7)和Python从Bing Web搜索中获取特色片段的示例代码:
import requests
import json
# Replace with your own subscription key and endpoint.
subscription_key = 'INSERT_SUBSCRIPTION_KEY_HERE'
endpoint = 'https://api.cognitive.microsoft.com/bing/v7.0/search'
# Define a query. In this example, the query searches for "what is the capital of France".
query = "what is the capital of France"
# Define the parameters for the request.
params = {
'q': query,
'mkt': 'en-US',
'count': 1,
'offset': 0,
'answerCount': 1,
'responseFilter': 'Answer',
'textDecorations': False,
'textFormat': 'Raw'
}
# Define the headers.
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
}
# Send the request and get the response.
response = requests.get(endpoint, headers=headers, params=params)
response.raise_for_status()
# Extract the answer from the JSON response.
search_results = response.json()
answer = search_results['answers'][0]['value']
# Print the answer.
print('Answer: ' + answer)
这个例子返回的结果是一个特色片段,其中包含问题的答案,如“巴黎”。
请注意,要成功获取特色片段,必须使用“responseFilter”查询参数并将其设置为“Answer”(默认值为“WebPages”)。