在Python中正确格式化http.client.HTTPSConnection

在Python中正确格式化http.client.HTTPSConnection,python,python-3.x,Python,Python 3.x,总的来说,我试图从Python 3.5.1::Anaconda 4.0.0(32位)调用MS认知。我到处找了找,试图把它合并起来 要调用API,需要添加下面标记为##的帐户密钥, 但是,要正确格式化正文,您可能不需要帐户密钥。下面代码的一大部分来自示例代码 请求主体应该是 body = { "documents": [ { "language": "en", "id": "1", "text": "One

总的来说,我试图从Python 3.5.1::Anaconda 4.0.0(32位)调用MS认知。我到处找了找,试图把它合并起来

要调用API,需要添加下面标记为##的帐户密钥, 但是,要正确格式化正文,您可能不需要帐户密钥。下面代码的一大部分来自示例代码

请求主体应该是

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


我对上面的代码做了2个修改,使其能够工作。1) 我把我的情妇和身体搞混了。2) 我需要在我的帖子中添加str(body_文档)。都是初学者的错误

我对上面的代码做了2个修改,使其能够工作。1) 我把我的情妇和身体搞混了。2) 我需要在我的帖子中添加str(body_文档)。都是初学者的错误

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))