任何人都可以帮助我使用Python将个性洞察API的json输出存储到csv吗?

时间:2015-06-07 16:32:15

标签: python json csv ibm-watson personality-insights

我已经在Bluemix中部署了我的个性洞察服务App,我可以调用post命令来发送文本。我想将数据的输出保存到csv,我已经通过了Personality API的API文档,但是我无法理解我哪里出错了。任何人都可以帮我将输出存储到csv文件。

这是我在Python中使用的代码。

#!/usr/bin/env python
# coding: utf-8

import requests
import json
import csv

response = requests.post("https://gateway.watsonplatform.net/personality-insights/api/v2/profile",
                         auth=("user-id", "password"),
                         headers={"content-type": "application/json", "Accept": "text/csv"},
                         data = "text to be analyzed"
                         )

jsonProfile = json.loads(response.text)

with open('test1234.csv', 'w') as f:
    for row in jsonProfile:
        f.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

您已从请求中获取带有Accept: text/csv请求标头的CSV数据。您只需要将此直接输出到一个文件,无需使用任何库(Personality Insights已经为您格式化了这一点!)。

以下是修改后的代码:

response = requests.post("https://gateway.watsonplatform.net/personality-insights"+
                         "/api/v2/profile?headers=True",
     auth = ("userid", "password"),
     headers = {"content-type": "text/plain", "Accept": "text/csv"},
     data = "replace your text here"
     )
with open('personality-insights.csv', 'w') as f:
    print >> f, response.text

另请注意在URL中添加?headers=True作为查询参数:这将输出列名称 - 您可能会发现这很有用(如果您连接多个API调用的输出,则省略此参数并获得原始示例中的值。)