我编写了一组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 –