基于 IBM Watson/Bluemix 的 Python 应用程序在查询 Tone Analyzer API 时返回



我有以下代码,其中用户名、密码和 URL 值更新为直接从 IBM Watson Service 凭据复制的值。由于某种原因,我收到以下错误。

法典:

import requests
import json
def analyze_tone(text):
username = 'username-copied-from-watson'
password = 'service-password-copied-from-watson'
watsonUrl = 'https://gateway.watsonplatform.net/tone-analyzer/api'
headers = {"content-type": "text/plain"}
data = text
try:
r = requests.post(watsonUrl, auth=(username,password),headers = headers,
data=data)
return r.text
except:
return False
def welcome():
message = "Welcome to the IBM Watson Tone Analyzern"
print(message + "-" * len(message) + "n")
message = "How it works"
print(message)
message = "Perhaps a bit too aggressive in your emails? Are your blog posts a little too friendly? Tone Analyzer might be able to help. The service uses linguistic analysis to detect and interpret emotional, social, and writing cues found in text."
print(message)
print()
print("Have fun!n")
def display_results(data):
data = json.loads(str(data))
print(data)
for i in data['document_tone']['tone_categories']:
print(i['category_name'])
print("-" * len(i['category_name']))
for j in i['tones']:
print(j['tone_name'].ljust(20),(str(round(j['score'] * 100,1)) + "%").rjust(10))
print()
print()
def main():
welcome()
data = input("Enter some text to be analyzed for tone analysis by IBM Watson (Q to quit):n")
if len(data) >= 1:
if data == 'q'.lower():
exit
results = analyze_tone(data)
if results != False:
display_results(results)
exit
else:
print("Something went wrong")
main()

错误:

Enter some text to be analyzed for tone analysis by IBM Watson (Q to quit):
"I love hate you"
{u'sub_code': u'C00010', u'code': 404, u'error': u'Not Found'}
Traceback (most recent call last):
File "test.py", line 58, in <module>
main()
File "test.py", line 53, in main
display_results(results)

您的代码似乎存在一些问题。Watson Tone Analyzer 服务的 API 将以下内容列为 API 端点:

https://gateway.watsonplatform.net/tone-analyzer/api/v3/{method}

您缺少版本 3v3,我没有看到您提供任何方法。您还需要传入 API 版本。

我建议将官方的Python SDK用于IBM Watson服务。当您浏览该 GitHub 存储库时,您将找到音调分析器的示例。

最新更新