首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有谁能帮助我使用Python将个性洞察力API的json输出存储到csv?

有谁能帮助我使用Python将个性洞察力API的json输出存储到csv?
EN

Stack Overflow用户
提问于 2015-06-07 16:32:15
回答 1查看 985关注 0票数 0

我已经在Bluemix中部署了我的个性洞察力服务应用程序,我可以调用post命令发送文本。我想把数据的输出保存到csv,我已经看过了Personality的API文档,但是我不知道我哪里出错了。谁能帮我把输出存储到csv文件。

下面是我在Python中使用的代码。

代码语言:javascript
复制
#!/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)

请帮帮我。

EN

回答 1

Stack Overflow用户

发布于 2015-06-07 21:35:04

您已经从请求中获得CSV数据,并带有Accept: text/csv请求头。您所需要的只是直接将其输出到一个文件中,而不需要使用任何库(Personality已经为您格式化了此文件!)

下面是一个经过修改的代码,可以工作:

代码语言:javascript
复制
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调用的输出,那么就省略这个参数,只获取原始示例中的值)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30695893

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档