Python 使用请求模块导出csv
我是Python的初学者,我一直在尝试将数据导出到csv文件,但我不知道如何去掉所有括号和逗号分隔的文件。理想情况下,我需要两列:一列包含“count”的所有值,另一列包含“month”的值 谢谢你的建议 我的代码:Python 使用请求模块导出csv,python,export-to-csv,python-requests,Python,Export To Csv,Python Requests,我是Python的初学者,我一直在尝试将数据导出到csv文件,但我不知道如何去掉所有括号和逗号分隔的文件。理想情况下,我需要两列:一列包含“count”的所有值,另一列包含“month”的值 谢谢你的建议 我的代码: from sunlight import capitolwords import requests import csv r = requests.get ('http://capitolwords.org/api/1/dates.json?phrase=guns&sta
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
结果:
['{']
[' "results": [']
[' {']
[' "count": 62.0', '']
[' "month": "201212"']
[' }', '']
[' {']
[' "count": 36.0', '']
[' "month": "201207"']
[' }', '']
[' {']
[' "count": 35.0', '']
[' "month": "201112"']
[' }', '']
[' {']
[' "count": 27.0', '']
[' "month": "201202"']
[' }', '']
[' {']
[' "count": 27.0', '']
由于响应是Json,请使用以下内容加载Json数据:
data = r.json()["results"] # read the json response and keep the results part
然后写入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"]])
如果CSV包不是强制性的,您可以使用正常的输出操作,并使用CSV保存文件。CSV只是一个用逗号分隔列的txt文件 这是你怎么做到的
with open("abc.csv","w+") as fh:
str = "count: 62.0"
str = str + ",month: 201212"
fh.writeline(str)
我想对@thikonom上面所说的话做一点解释
r.json()
当您使用r.json()时,您将r中的内容解释为json。提示您发送的查询字符串中的数据为json。如果您熟悉json,那么结果也类似于json
r.json()["results"]
现在,您告诉json使用键results搜索您的结果r以查找字典。在这里,能够看到您对查询的期望是一个很大的帮助,您粘贴到上面窗口的结果中会显示结果。我们还认识到,它以字典显示的标准方式显示:
{'results': [{'month': '201212', 'count': 62.0}...
等等结果在本例中是键,在:之后的其余数据被视为键的值。使用~>r.json()[“results”]可以说您正在尝试导出数据,但您的代码只显示一个CSV阅读器。怎么回事?在任何情况下,csv.reader
的第一个参数必须是文件句柄,而不是代码中的字符串列表。
f.writerow([elem["count"], elem["month"]])