1

Overall, I'm trying to invoke the MS Cognitive key phrases API from Python 3.5.1 :: Anaconda 4.0.0 (32-bit). I looked everywhere and tried to incorporate this stackoverflow response.

To call the API your account key below marked as ## needs to be added from here, however to format the body correctly you probably don't need the account key. A good portion of the code below is from sample code.

Request body should look like

body = {
  "documents": [
        {
            "language": "en",
            "id": "1",
            "text": "One line of text."
        },
        {
            "language": "en",
            "id": "2",
            "text": "another line of text."
        }
    ]
}

my code <it now works!!>

import sys
import os.path
import http.client
import urllib.request
import urllib.parse
import urllib.error
import base64
import json

subscription_key = '##'

headers = {
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': subscription_key
}

#input text is: ID | text to analyze. How my input file is formatted.
input_text = ["100|One line of text.", "101|another line of text."]


# Inputs holds the params to call the web service in bulk.
body = []

indx = 1

for line in input_text:
    input_text = line.split("|")
    print ('-----\n')
    print ("Input text is:", input_text)
    input_text_analyze = input_text[1]
    print ('\nInput text to be analyzed:', input_text_analyze)
    body.append({ "language" : "en", "id" : str(indx), "text" : input_text_analyze })
    indx = indx + 1

print ('-----\n')
print ('\nBody has', body)

print ("Calling API to get keywords...")

body_documents = { 'documents': body }

print ("\nParams:", body_documents)

params = urllib.parse.urlencode({ })

try:
    conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com')
    conn.request("POST", "/text/analytics/v2.0/keyPhrases?%s" % params, str(body_documents), headers)
    response = conn.getresponse()
    keyword_obj = response.read()
    print("Returned keyword_obj is: ", keyword_obj)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

1 Answer 1

0

I made 2 changed to the code above that allow it to work. 1) I was getting my params and body mixed up. 2) I needed to add str(body_documents) in my post. Both beginner mistakes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.