热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

使用请求模块导出csv-Usingrequestsmoduletoexportcsv

ImabeginnertoPythonandIhavebeentryingtoexportmydatatoacsvfilebutIcantfigureo

I'm a beginner to Python and I have been trying to export my data to a csv file but I can't figure out how to get rid of all the brackets and my comma separated. Ideally I need two columns: one with all values for "count" and one with values for "month".

我是Python的初学者,我一直在尝试将我的数据导出到csv文件,但我无法弄清楚如何摆脱所有括号和我的逗号分隔。理想情况下,我需要两列:一列具有“count”的所有值,另一列具有“month”的值。

Any advice appreciated.

任何建议表示赞赏

My code:

我的代码:

from sunlight import capitolwords
import requests
import csv

r = requests.get ('http://capitolwords.org/api/1/dates.json?phrase=guns&start_date=2011-  
12-01&end_date=2013-01-
15&granularity=month&sort=count&apikey=ab02633fb17841d09f4c3660e0384ae5')
data = r.text

ifile = open('guns.csv', 'rb')
reader = csv.reader(data.splitlines(), delimiter=',')
for row in reader:
    print row

Result:

结果:

  ['{']
  ['    "results": [']
  ['        {']
  ['            "count": 62.0', '']
  ['            "month": "201212"']
  ['        }', '']
  ['        {']
  ['            "count": 36.0', '']
  ['            "month": "201207"']
  ['        }', '']
  ['        {']
  ['            "count": 35.0', '']
  ['            "month": "201112"']
  ['        }', '']
  ['        {']
  ['            "count": 27.0', '']
  ['            "month": "201202"']
  ['        }', '']
  ['        {']
  ['            "count": 27.0', '']

3 个解决方案

#1


6  

Since the response is a Json, load the json data with:

由于响应是Json,因此使用以下命令加载json数据:

data = r.json()["results"] # read the json response and keep the results part

and then write to the csv file:

然后写入csv文件:

with open("guns.csv", "wb") as csvfile:
    f = csv.writer(csvfile)
    f.writerow(["Count", "Month"]) # write the headers if you like
    for elem in data:
        f.writerow([elem["count"], elem["month"]])

#2


1  

if CSV package is not mandatory you can use the normal output operation and save the file with CSV. CSV is just a txt file with cols seperated by comma.

如果CSV包不是必需的,您可以使用正常输出操作并使用CSV保存文件。 CSV只是一个txt文件,其中cols由逗号分隔。

here how you can do this.

在这里你如何做到这一点。

with open("abc.csv","w+") as fh:
    str = "count: 62.0"

    str = str + ",month: 201212" 

    fh.writeline(str)

#3


1  

I'd like to add a bit of explanation to what @thikonom has said above.

我想对@thikonom上面所说的内容添加一些解释。

r.json()

When you're using r.json(), you're interpreting what is in r as json. A hint was given to your data being json in the query string you sent. If you're familiar with json, the results also look like json.

当你使用r.json()时,你正在将r中的内容解释为json。在您发送的查询字符串中,您的数据被提示为json。如果你熟悉json,结果也看起来像json。

r.json()["results"]

You're now telling json to search your results r for the dictionary with the key: results. Being able to see what you're expecting from the query is a big help here, where results is shown in the results you've pasted into the window above. We also recognize that it's displayed in the standard way that a dictionary is shown:

您现在告诉json使用关键字搜索结果r中的字典:结果。能够看到您对查询的期望是一个很大的帮助,其中结果显示在您粘贴到上面窗口的结果中。我们也认识到它以标准方式显示字典:

{'results': [{'month': '201212', 'count': 62.0}...

and so on. results in this case is the key, the rest of the data after the : is considered the key's value. Using ~> r.json()["results"] <~ returns results value. However, you'll notice that 'month' and 'count' are also wrapped in {}, meaning they are each in themselves key, value pairs. This means you've got dictionaries nested within dictionaries!

等等。在这种情况下结果是关键,其后的数据是:被认为是键的值。使用〜> r.json()[“results”] <〜返回结果值。但是,您会注意到'month'和'count'也包含在{}中,这意味着它们本身就是键值对。这意味着你有词典嵌套在词典中!

f.writerow([elem["count"], elem["month"]])

Going through, row by row, pulling out the value for both keys: count and month, which you then store into your *.csv file.

逐行完成,拉出两个键的值:count和month,然后存储到* .csv文件中。

Hope this may help somebody else!

希望这可以帮助别人!


推荐阅读
  • 如何查询zone下的表的信息
    本文介绍了如何通过TcaplusDB知识库查询zone下的表的信息。包括请求地址、GET请求参数说明、返回参数说明等内容。通过curl方法发起请求,并提供了请求示例。 ... [详细]
  • SpringMVC接收请求参数的方式总结
    本文总结了在SpringMVC开发中处理控制器参数的各种方式,包括处理使用@RequestParam注解的参数、MultipartFile类型参数和Simple类型参数的RequestParamMethodArgumentResolver,处理@RequestBody注解的参数的RequestResponseBodyMethodProcessor,以及PathVariableMapMethodArgumentResol等子类。 ... [详细]
  • 本文介绍了如何使用JSONObiect和Gson相关方法实现json数据与kotlin对象的相互转换。首先解释了JSON的概念和数据格式,然后详细介绍了相关API,包括JSONObject和Gson的使用方法。接着讲解了如何将json格式的字符串转换为kotlin对象或List,以及如何将kotlin对象转换为json字符串。最后提到了使用Map封装json对象的特殊情况。文章还对JSON和XML进行了比较,指出了JSON的优势和缺点。 ... [详细]
  • 图像因存在错误而无法显示 ... [详细]
  • 本文介绍了一种在PHP中对二维数组根据某个字段进行排序的方法,以年龄字段为例,按照倒序的方式进行排序,并给出了具体的代码实现。 ... [详细]
  • 超级简单加解密工具的方案和功能
    本文介绍了一个超级简单的加解密工具的方案和功能。该工具可以读取文件头,并根据特定长度进行加密,加密后将加密部分写入源文件。同时,该工具也支持解密操作。加密和解密过程是可逆的。本文还提到了一些相关的功能和使用方法,并给出了Python代码示例。 ... [详细]
  • 本文介绍了NetCore WebAPI开发的探索过程,包括新建项目、运行接口获取数据、跨平台部署等。同时还提供了客户端访问代码示例,包括Post函数、服务器post地址、api参数等。详细讲解了部署模式选择、框架依赖和独立部署的区别,以及在Windows和Linux平台上的部署方法。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文介绍了Redis的基础数据结构string的应用场景,并以面试的形式进行问答讲解,帮助读者更好地理解和应用Redis。同时,描述了一位面试者的心理状态和面试官的行为。 ... [详细]
  • 本文介绍了使用PHP实现断点续传乱序合并文件的方法和源码。由于网络原因,文件需要分割成多个部分发送,因此无法按顺序接收。文章中提供了merge2.php的源码,通过使用shuffle函数打乱文件读取顺序,实现了乱序合并文件的功能。同时,还介绍了filesize、glob、unlink、fopen等相关函数的使用。阅读本文可以了解如何使用PHP实现断点续传乱序合并文件的具体步骤。 ... [详细]
  • 欢乐的票圈重构之旅——RecyclerView的头尾布局增加
    项目重构的Git地址:https:github.comrazerdpFriendCircletreemain-dev项目同步更新的文集:http:www.jianshu.comno ... [详细]
  • 本文介绍了响应式页面的概念和实现方式,包括针对不同终端制作特定页面和制作一个页面适应不同终端的显示。分析了两种实现方式的优缺点,提出了选择方案的建议。同时,对于响应式页面的需求和背景进行了讨论,解释了为什么需要响应式页面。 ... [详细]
author-avatar
VEACEN晨k
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有