作者:VEACEN晨k | 来源:互联网 | 2023-10-10 14:17
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
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!
希望这可以帮助别人!