[英]POST request to IBM Watson Relationship extraction returns error
在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相同的方法,並且有效。
有任何想法嗎?
謝謝
這是應該工作的代碼的更新副本:
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)
基本上,我更改了要發布的有效負載以添加一些缺失值。
希望這可以幫助!
如果您不想使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.