|
1 | | -#Copyright (c) Microsoft Corporation. All rights reserved. |
2 | | -#Licensed under the MIT License. |
| 1 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +# Licensed under the MIT License. |
3 | 3 |
|
4 | | -import http.client |
5 | 4 | import json |
6 | 5 | import os |
7 | 6 | from pprint import pprint |
| 7 | +import requests |
8 | 8 | import urllib.parse |
9 | 9 |
|
10 | 10 | ''' |
11 | | -This sample uses the Bing Spell Check API to check the spelling of query words and then suggests corrections. |
| 11 | +This sample uses the Bing Spell Check API to check the spelling of query words |
| 12 | +and then suggests corrections with a scored confidence. |
12 | 13 | Bing Spell Check API: https://dev.cognitive.microsoft.com/docs/services/5f7d486e04d2430193e1ca8f760cd7ed/operations/57855119bca1df1c647bc358 |
13 | 14 | ''' |
14 | 15 |
|
15 | | -text = 'Hollo, wrld!' |
16 | | - |
17 | | -params = {'mkt': 'en-US', 'mode': 'proof', 'text': text} |
18 | | - |
19 | | -# Add your Bing Spell Check subscription key anf endpoint to your environment variables. |
| 16 | +# Add your Bing Spell Check subscription key and endpoint to your environment variables. |
20 | 17 | key = os.environ['BING_SPELL_CHECK_SUBSCRIPTION_KEY'] |
21 | | -host = os.environ['BING_SPELL_CHECK_ENDPOINT'] |
22 | | -host = host.replace('https://', '') |
23 | | -path = '/bing/v7.0/spellcheck' |
| 18 | +endpoint = os.environ['BING_SPELL_CHECK_ENDPOINT'] + '/bing/v7.0/spellcheck' |
| 19 | + |
| 20 | +# Query you want spell-checked. |
| 21 | +query = 'Hollo, wrld!' |
24 | 22 |
|
25 | | -headers = {'Ocp-Apim-Subscription-Key': key, |
26 | | -'Content-Type': 'application/x-www-form-urlencoded'} |
| 23 | +# Construct request |
| 24 | +params = urllib.parse.urlencode( { 'mkt': 'en-US', 'mode': 'proof', 'text': query } ) |
| 25 | +headers = { 'Ocp-Apim-Subscription-Key': key, |
| 26 | + 'Content-Type': 'application/x-www-form-urlencoded' } |
27 | 27 |
|
28 | | -# The headers in the following example |
29 | | -# are optional but should be considered as required: |
| 28 | +# Optional headers |
30 | 29 | # |
31 | 30 | # X-MSEdge-ClientIP: 999.999.999.999 |
32 | 31 | # X-Search-Location: lat: +90.0000000000000;long: 00.0000000000000;re:100.000000000000 |
33 | 32 | # X-MSEdge-ClientID: <Client ID from Previous Response Goes Here> |
34 | 33 |
|
35 | | -conn = http.client.HTTPSConnection(host) |
36 | | -params = urllib.parse.urlencode (params) |
37 | | -conn.request ("POST", path, params, headers) |
38 | | -response = conn.getresponse () |
39 | | -pprint(json.loads(response.read())) |
| 34 | +# Call the API |
| 35 | +try: |
| 36 | + response = requests.get(endpoint, headers=headers, params=params) |
| 37 | + response.raise_for_status() |
| 38 | + |
| 39 | + print("\nHeaders:\n") |
| 40 | + print(response.headers) |
| 41 | + |
| 42 | + print("\nJSON Response:\n") |
| 43 | + pprint(response.json()) |
| 44 | +except Exception as ex: |
| 45 | + raise ex |
0 commit comments