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'。 –