我编写了一组Python函数来与Bluemix/Watson 概念洞察API进行交互。我能够生成一个令牌,并使用它从服务器获得结果,但是结果很糟糕:当我将相同的信息插入到他们的招摇测试实用程序中时,它远不如我所得到的那么好。
我怀疑我发送请求的方式有问题,但我不知道具体是什么。代码如下。首先,来自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)输出差异的完整演示是这里。完整的代码基是这里。我对请求库不是很有经验:在Pythonic端的某个地方是否有一个微妙的错误?
IBM文档的相关部分是这里。
发布于 2016-03-15 19:16:40
正如@engineerc所建议的那样,您将发送一个dict()作为data。引用您的评论data=text.encode(encoding='UTF-8', errors='ignore')是解决问题的方法。
另一方面,请不要使用 https://watson-api-explorer.mybluemix.net,它是一个代理应用程序,我们使用它来承载swagger文档。
服务网址是:https://gateway.watsonplatform.net/concept-insights/api
此外,我们还有一个支持ConceptInsights和annotate_text调用的python。
它是一个pip模块,所以您将这样做:
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))https://stackoverflow.com/questions/33194181
复制相似问题