Python:将计数器写入csv文件

Python:将计数器写入csv文件,python,csv,dictionary,counter,Python,Csv,Dictionary,Counter,我有一个csv数据文件,其中包含列'number','color','number2','foo','bar',如下所示: 12, red, 124, a, 15p 14, blue, 353, c, 7g 12, blue, 125, d, 65h 12, red, 124, c, 12d 我想计算number、color和number2同时出现的次数,例如,上面列表的输出将是:'12,红色,124:2','14,蓝色,353:1','12,蓝色,125:1'。我使用以下方法完成了此操作:

我有一个csv数据文件,其中包含列
'number'
'color'
'number2'
'foo'
'bar'
,如下所示:

12, red, 124, a, 15p
14, blue, 353, c, 7g
12, blue, 125, d, 65h
12, red, 124, c, 12d
我想计算number、color和number2同时出现的次数,例如,上面列表的输出将是:
'12,红色,124:2','14,蓝色,353:1','12,蓝色,125:1'
。我使用以下方法完成了此操作:

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)
这给了我:

Counter({(‘12’,’red’,’135’): 21, (‘15’,’blue’,’152’):18, (‘34’,’green’,’123’):16 etc})
这很好,但我想把它写进一个文件。我希望这个文件有4列:数字、颜色、数字2和计数。我意识到这是一个常见的问题,我在其他线程上尝试了一些不同的方法,但都没有奏效

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)

两者都告诉我错误

    return self.writer.writerow(self._dict_to_list(rowdict))
TypeError: 'str' does not support the buffer interface
我也尝试过使用pickle:

import pickle
with open('newfile.csv','wb') as outputfile:
    pickle.dump(outfile1, outputfile)
给我乱七八糟的文件

我目前的尝试是使用

writer=csv.DictWriter(newfile, outfile1)
for line in outfile1:
    writer.writerow(line)
但这给了我一个关于字段名的错误


我知道这是一个常见的问题,我意识到我之所以挣扎是因为我真的不知道自己在做什么——自从我使用python已经有几年了,我已经忘记了很多。任何帮助都将不胜感激。

首先,主要问题的原因是:

TypeError: 'str' does not support the buffer interface
如果是以二进制模式打开文件,则应以文本模式打开文件(不带
b

第二,我想说的是,由于你的词典是以怎样的方式创建的,所以使用normal比在你的情况下更容易

将结果写入csv的一种方法是-

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

对我来说,上述解决方案不起作用。它将单词的所有字符拆分为单独的列,因此输出是“单独列中的每个字符后跟计数”,而不是一列中的整个单词后跟计数。这可能是由于我可能犯的一些其他错误。 然而,对我来说,下面的代码起作用了:

    with open(outfile, encoding='utf-8-sig', mode='w') as fp:
        fp.write('KMC,freq\n')  
        for tag, count in cnt.items():  
            fp.write('{},{}\n'.format(tag, count))  
我希望这对其他人有帮助

import csv
假设count是Python 3计数器。
如果键是字符串,则不要在其包含的每个字符中拆分它:

with open(root+'counter_test.csv','w') as csvfile:
    writer=csv.writer(csvfile)
    for key, value in count.items():
        writer.writerow([key] + [value])
更简单的是(注意到writerows()函数的“s”):


只需使用for循环,我们就可以将序列计数器添加到CSV reade中 下面的代码将计数器解压缩到csv文件

import csv

x=0
reader = csv.reader(open("c:/path/abc.csv"))
for raw in reader:
    x += 1
    print(raw)
    print(x)
上面的代码将按如下方式显示输出

['id','fname','lname'] 1. ['1','a','x'] 2. ['2','b','y'] 3. ['3','c','z']
4

如果要传递生成器/序列,请使用“writerow”,而不是“writerow”。Pickle文件对人们来说是胡言乱语,但如果您想加载到其他地方,Pickle可以读取。DictWriter的参数是:csvfile,fieldnames,…,因此第一个参数是文件,第二个参数是字段名列表。
with open(root+'counter_test.csv','w') as csvfile:
    writer=csv.writer(csvfile)
    writer.writerows(count.items())
import csv

x=0
reader = csv.reader(open("c:/path/abc.csv"))
for raw in reader:
    x += 1
    print(raw)
    print(x)