总的来说,我正在尝试调用Python 3.5.1中的MS Cognitive Key Phrases API::Anaconda 4.0.0(32位)。我到处寻找,并试图合并这个堆栈溢出响应。
要调用 API,需要从此处添加下面标记为 ## 的帐户密钥,但是,要正确格式化正文,您可能不需要帐户密钥。下面的代码中有很大一部分来自示例代码。
请求正文应如下所示
body = {
"documents": [
{
"language": "en",
"id": "1",
"text": "One line of text."
},
{
"language": "en",
"id": "2",
"text": "another line of text."
}
]
}
我的代码<现在可以工作了!!>>
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))
我对上面的代码进行了 2 次更改,使其能够工作。 1)我把我的参数和身体弄混了。 2)我需要在我的帖子中添加 str(body_documents)。都是初学者的错误。