我有一个这种格式的 python 字典:
{
"intents": [
{
"name": "ER111-Test1",
"created": "2017-08-18T18:09:36.155Z",
"updated": "2017-08-18T18:09:41.755Z",
"description": null
},
{
"name": "ER2222-Test2",
"created": "2017-08-18T18:05:48.153Z",
"updated": "2017-08-18T18:06:06.004Z",
"description": null
}
],
"pagination": {
"refresh_url": "/v1/workspaces/9978a49e-ea89-4493-b33d-82298d3db20d/intents?version=2017-08-21"
}
}
我正在尝试删除“ER111”和“ER2222”值并重新上传。我正在从 IBM Watson API 运行 this 方法。
代码的运行率为 99%,但在最后一步不允许我上传。
response = ...
names = [d['name'] for d in response['intents']]
for name in names:
fixed_name = re.sub('ER\d{4,5}-', ' ', name) #this works to remove the prefix
print(name + ' ' + fixed_name) #testing it works, it does
response = conversation.update_intent(workspace_id='1234567',
intent=str(name),
new_intent=str(fixed_name)) #fails here with code 400
在最后一行,我们失败并显示“错误:无效的请求正文,代码:400”。如果我对值进行硬编码而不是使用变量,它就会起作用。我尝试过添加引号和其他一些东西,但似乎无法让它很好地发挥作用。
有什么想法可能会导致这种情况吗?
最佳答案
看来 Watson 不喜欢您发送的数据中存在前导空格。对于初学者,请看这里 -
fixed_name = re.sub('ER\d{4,5}-', ' ', name)
# ^
由于 name
以 ER...
开头,因此该模式将被替换为前导空格。您应该做的是将其替换为空字符串 ''
。
但是,更好的方法是使用 str.split
在第一个 -
上进行拆分。方法如下 -
>>> "ER111-Test1".split('-', 1)[-1]
'Test1'
关于python - 从 Python 调用 IBM Watson 的 update_intent 函数给出 "Invalid Request Body",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47792415/