Python:将计数器写入csv文件 [英] Python: Writing Counter to a csv file
问题描述
我有一个csv文件的数据,有'number'
,'color'
c $ c>'number2','foo'
,'bar'
看起来像:
12,red,124,a,15p
14,blue,353,c,7g
12,blue,125,d,65h
12,red,124,c,12d
$ b b
我想计算number,color和number2的次数,例如,上面列表的输出将是: '12,red,124:2',' 14,蓝色,353:1','12,蓝色,125:1'
。我使用这样做:
import csv
datafile = open('myfile.csv','r ')
usefuldata = []
在数据文件中的行:
usefuldata.append(line)
from collections import Counter
outfile1 = Counter((line [1] ,line [2],line [3])for use in usefuldata)
print(outfile1)
这给我:
计数器({('12','red','135'): ('15','blue','152'):18,('34','green','123'):16 etc})
这是伟大的,但我想把它写入一个文件。我想文件有4列:number,color,number2和count。我意识到这是一个常见的问题,我尝试了其他线程建议的几种不同的方法,但没有一个工作。
Newfile = open('newfile.csv','wb')
fieldnames = ['a','b']
csvwriter = csv.DictWriter(newfile,delimiter =',',fieldnames = fieldnames )
csvwriter.writerow(dict((fn,fn)for fn in fieldnames))
outfile1中的行:
csvwriter.writerow(row)
并且
.csv','wb')as csvfile:
fieldnames = ['number','color','number2']
writer = csv.DictWriter(csvfile,fieldnames = fieldnames)
)
countwriter = csv.writer(csvfile,delimiter(1),line [2],line [3] =',')
countwriter.writerow(outfile1)
/ p>
return self.writer.writerow(self._dict_to_list(rowdict))
TypeError:'str'不支持缓冲区接口
我也试过使用pickle:
import pickle
with open('newfile.csv','wb')as outputfile:
pickle.dump(outfile1,outputfile)$ b $
我目前的尝试是:
使用writer = csv.DictWriter(newfile,outfile1)
for outfile1:
writer .writerow(line)
但这给我一个关于fieldnames的错误。
我知道这是一个常见的问题,我意识到我只是在努力,因为我真的不知道我在做什么 - 这已经几年了,因为我使用python和我忘了这么多。
解决方案首先,主要问题的原因 -
TypeError:'str'不支持缓冲区接口
是以二进制模式打开文件,应以文本模式打开文件(不含
b
)。
其次,我会说更容易使用正常
csv.writer
csv.DictWriter()
。
将结果写入csv的方法是 -
#假设您先前创建了计数器你想写
#lets说你将计数器存储在一个名为cnter
的变量中open('newfile.csv','w')as csvfile:
fieldnames = ['number ','color','number2','count']
writer = csv.writer(csvfile)
writer.writerow(fieldnames)
for cnter.items :
writer.writerow(list(key)+ [value])
I have a csv file of data that has the columns
‘number’
,’colour’
,’number2’
,’foo’
,’bar’
, which looks like:12, red, 124, a, 15p 14, blue, 353, c, 7g 12, blue, 125, d, 65h 12, red, 124, c, 12d
I want to count the number of times number, colour and number2 occur together, so for example, the output from the above list would be:
’12, red, 124 :2’,’14, blue, 353: 1’, ’12, blue, 125: 1’
. I’ve done this by using:import csv datafile=open('myfile.csv','r') usefuldata=[] for line in datafile: usefuldata.append(line) from collections import Counter outfile1=Counter((line[1],line[2],line[3]) for line in usefuldata) print(outfile1)
This gives me :
Counter({(‘12’,’red’,’135’): 21, (‘15’,’blue’,’152’):18, (‘34’,’green’,’123’):16 etc})
Which is great, but I’d like to write this out to a file. I'd like the file to have 4 columns: number, colour, number2, and count. I realise this is a common question and I’ve tried a few different approaches suggested on other threads, but none have worked.
Newfile=open(‘newfile.csv’,’wb’) fieldnames=['a','b'] csvwriter=csv.DictWriter(newfile, delimiter=',', fieldnames=fieldnames) csvwriter.writerow(dict((fn,fn) for fn in fieldnames)) for row in outfile1: csvwriter.writerow(row)
And
with open('newfile.csv','wb') as csvfile: fieldnames=['number','colour','number2'] writer=csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerow(Counter((line[1],line[2],line[3]) for line in usefuldata)) countwriter=csv.writer(csvfile, delimiter=', ') countwriter.writerow(outfile1)
Both give me the error
return self.writer.writerow(self._dict_to_list(rowdict)) TypeError: 'str' does not support the buffer interface
I've also tried using pickle:
import pickle with open('newfile.csv','wb') as outputfile: pickle.dump(outfile1, outputfile)
gives me gibberish files.
My current attempt is to use
writer=csv.DictWriter(newfile, outfile1) for line in outfile1: writer.writerow(line)
but this gives me an error about fieldnames.
I know this is a common question and I'm conscious that I'm only struggling because I really don't know what I'm doing- it has been a few years since I've used python and I've forgotten so much. Any help would be greatly appreciated.
解决方案First of all, the reason for the main issue -
TypeError: 'str' does not support the buffer interface
is that you are openning the file in binary mode, you should open the file in text mode ( without
b
).Secondly, I would say it would be easier to use normal
csv.writer
thancsv.DictWriter()
in your case, because of the way your dictionary is created.A way to write your result to csv would be -
#Assuming you have previously created the counter you want to write #lets say you stored the counter in a variable called cnter with open('newfile.csv','w') as csvfile: fieldnames=['number','colour','number2','count'] writer=csv.writer(csvfile) writer.writerow(fieldnames) for key, value in cnter.items(): writer.writerow(list(key) + [value])
这篇关于Python:将计数器写入csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!