The Web Language Model API is used in the Microsoft Cognitive Services, and allows for the analysis of text. In this example we determine the next 20 words in a phrase:
Web Language Model API (Next word) |
Coding
The following gives an outline of the Python code:
import httplib, urllib, base64 import sys import json headers = { # Request headers 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': 'KEY', } rtns=20 text="this is the next " if (len(sys.argv)>1): text=str(sys.argv[1]) params = urllib.urlencode({ # Request parameters 'model': 'body', 'words': text, 'order': '2', 'maxNumOfCandidatesReturned': str(rtns), }) try: conn = httplib.HTTPSConnection('westus.api.cognitive.microsoft.com') conn.request("POST", "/text/weblm/v1.0/generateNextWords?%s" % params, "{body}", headers) response = conn.getresponse() data = response.read() conn.close() d= json.loads(data) print text+"...." for x in range(0, rtns): print '%3s %-15s Probablity: %10s' % (str(x+1),d['candidates'][x]['word'],str(d['candidates'][x]['probability'])) except Exception as e: print("[Errno {0}] {1}".format(e.errno, e.strerror))