我編寫了一組Python函數來與Bluemix/Watson Concept Insights API進行交互。我能夠生成一個令牌並使用它來從服務器獲取結果,但結果很糟糕:當我將相同的信息插入Swagger testing utility時,結果遠不及我所得到的結果。使用Python調用IBM Watson Concept Insights的annotate_text
我懷疑發送我的請求的方式有問題,但我不知道是什麼。代碼如下。首先,從event_insight_lib.py
:
def importCredentials(filename='credentials.json'):
if filename in [f for f in os.listdir('.') if os.path.isfile(f)]:
data = json.load(open(filename))['concept_insights'][0]['credentials']
return data
def generateToken(filename='credentials.json'):
credentials = importCredentials(filename)
r = requests.get("https://gateway.watsonplatform.net/authorization/api/v1/token\?url=https://stream.watsonplatform.net/concept-insights/api", auth=(credentials['username'], credentials['password']))
if r.status_code == requests.codes.ok:
return r.text
def annotateText(text, token, content_type = 'text/plain'):
base_url='https://watson-api-explorer.mybluemix.net/concept-insights/api/v2/graphs/wikipedia/en-20120601/annotate_text'
headers = {'X-Watson-Authorization-Token': token, 'Content-Type': content_type}
r = requests.post(base_url, headers=headers, data={'body': text})
return r.text
這些方法是由執行event_insight.py
:
token = event_insight_lib.generateToken()
ret = event_insight_lib.annotateText("""long string being concept-analyzed...""", token)
print(ret)
在輸出差異的充分論證是here。完整的代碼庫是here。我對Requests庫不是很有經驗:Pythonic的某個地方有一個微妙的錯誤嗎?
IBM文檔的相關部分是here。
你傳遞的字典中的'您的要求,中data'參數,將要形成數據編碼。嘗試傳遞'data = text'。 http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests – engineerC
你是對的!將該段更改爲'data = text.encode(encoding ='UTF-8',errors ='ignore')'似乎解決了這個問題。 –
我們有一個我們正在開發的Python SDK .Concept Insights在那裏不受支持,但我希望下週有希望。 https://github.com/watson-developer-cloud/python-sdk –