gpt4 book ai didi

python - 使用请求模块导出 csv

转载 作者:行者123 更新时间:2023-11-28 20:08:11 25 4
gpt4 key购买 nike

我是 Python 的初学者,我一直在尝试将我的数据导出到 csv 文件,但我不知道如何去掉所有括号和逗号分隔。理想情况下,我需要两列:一列包含“count”的所有值,另一列包含“month”的值。

感谢任何建议。

我的代码:

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"]])

关于python - 使用请求模块导出 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14550050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com