1

我編寫了一組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

+2

你傳遞的字典中的'您的要求,中data'參數,將要形成數據編碼。嘗試傳遞'data = text'。 http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests – engineerC

+0

你是對的!將該段更改爲'data = text.encode(encoding ='UTF-8',errors ='ignore')'似乎解決了這個問題。 –

+1

我們有一個我們正在開發的Python SDK .Concept Insights在那裏不受支持,但我希望下週有希望。 https://github.com/watson-developer-cloud/python-sdk –

回答

2

由於@engineerc建議您發送dict()作爲data。引用您的評論data=text.encode(encoding='UTF-8', errors='ignore')是解決您的問題的方法。


在另一方面,請不要使用https://watson-api-explorer.mybluemix.net,這是我們用來託管招搖文檔的代理應用程序。
服務URL是: https://gateway.watsonplatform.net/concept-insights/api

同時,我們有一個python-SDK支持ConceptInsightsannotate_text通話。

這是一個點模塊,所以你會做什麼:

pip install watson-developer-cloud 

調用annotate_text它的那樣簡單:

import json 
from watson_developer_cloud import ConceptInsightsV2 as ConceptInsights 


concept_insights = ConceptInsights(
    username='YOUR SERVICE USERNAME', 
    password='YOUR SERVICE PASSWORD') 

annotations = concept_insights.annotate_text('IBM Watson won the Jeopardy television show hosted by Alex Trebek') 
print(json.dumps(annotations, indent=2)) 
+0

謝謝---我希望能夠更新[watsongraph](https://pypi.python.org/pypi/watsongraph/)(的產品所有這些探測)在下個月左右的某個時候使用'watson-developer-cloud'。 –