在Bluemix中,我试图从Python调用IBM Watson关系提取API。首先,我在Bluemix上创建一个应用程序,并将关系提取器api绑定到它。然后从API的下拉菜单中,我从实例化凭据中获取用户名和密码。我在下面的系列中用 bluemux-username 和 bluemix-password 替换了。我为此编写的Python代码如下:
import requests
import json
url="https://gateway.watsonplatform.net/relationship-extraction-beta/api/v1/sire/0"
username="bluemix_username"
password="bluemix_passowrd"
with open ("data.txt", "r") as myfile:
text=myfile.read().replace('\n', '')
raw_data = {
'contentItems' : [{
'contenttype' : 'text/plain',
'content': text
}]
}
input_data = json.dumps(raw_data)
response = requests.post(url, auth=(username, password), headers = {'content-type': 'application/json'}, data=input_data)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print("And you get an HTTPError: %s"% e.message)
然而,当我运行此操作时,我收到以下错误:
And you get an HTTPError: 400 Client Error: Bad Request
*注意:我对个性洞察 API采用了相同的方法,并且有效。
有什么想法吗?
由于
答案 0 :(得分:1)
以下是应该运行的代码的更新副本:
import requests
import json
url="https://gateway.watsonplatform.net/relationship-extraction-beta/api/v1/sire/0"
username="bluemix_username"
password="bluemix_passowrd"
with open ("data.txt", "r") as myfile:
text=myfile.read().replace('\n', '')
input_data = {
'sid' : 'ie-en-news',
'txt' : text
}
response = requests.post(url, auth=(username, password), data=input_data)
try:
response.raise_for_status()
print response.text
except requests.exceptions.HTTPError as e:
print("And you get an HTTPError: %s"% e.message)
基本上我更改了您发布的有效负载以添加一些缺失值。
希望这有帮助!
答案 1 :(得分:0)
如果您不想使用data.txt
并使用终端中的标准输入,您可以执行以下操作:
## -*- coding: utf-8 -*-
import os
import requests
import fileinput
class RelationshipExtractionService:
url = None
def __init__(self):
self.url = "https://gateway.watsonplatform.net/relationship-extraction-beta/api/v1/sire/0"
self.user = "<username>"
self.password = "<password>"
def extract(self, text):
data = {
'txt': text,
'sid': 'ie-en-news', # English News, for Spanish use: ie-es-news
'rt': 'xml',
}
r = requests.post(self.url,
auth=(self.user, self.password),
headers = {
'content-type': 'application/x-www-form-urlencoded'},
data=data
)
print("Request sent. Status code: %d, content-type: %s" %
(r.status_code, r.headers['content-type']))
if r.status_code != 200:
print("Result %s" % r.text)
raise Exception("Error calling the service.")
return r.text
if __name__ == '__main__':
service = RelationshipExtractionService()
for line in fileinput.input():
print service.extract(line)
<强>用法强>
简单文本分析:
echo "New York is awesome" | python main.py
您也可以管道文件:
cat article.txt | python main.py
从.txt到.xml:
cat article.txt | python main.py > article.xml