M.Huntz M.Huntz - 21 days ago 8
Python Question

Create a csv file with two columns | Counter mode

I worked on a code that is counting the occurrencies of words in a given text document and now I would like to save the output on a csv file with two columns: one for the words and one for their frequencies.

This is the code that I am trying to replicate:

from collections import Counter
counter = Counter(['spam', 'egg', 'spam', 'egg', 'python', 'egg'])

with open('wordfile.csv', 'w') as f:
writer = csv.writer(f, delimiter=' ')
writer.writerow(('word', 'count'))
writer.writerows(counter.most_common())


However, this is the output:

word countegg 3spam 2python 1


The output that I am trying to get should contain just two columns (one for the "word" adn one for the "frequency" and each row should contain a word and its occurrance in the text:

word, frequency,
the, 3165,
in, 1265,
of,1233,


When I print the output with the code:

print(open('wordfile.csv', 'rb').read())


I get:

b'word count\r\r\negg 3\r\r\nspam 2\r\r\npython 1\r\r\n')


As you can see there aren't the two columns for the word and the frequency.
I am using Windows and this is the Python version that I am using:
3.5.2 |Anaconda 4.1.1 (64-bit)

Answer

writer.writerow is expecting the list of columns for the row; in you snippet your are passing all the results ie. all the columns of all the items.

You need to iter over counter.items() to get the result you want:

import csv
from collections import Counter

counter = Counter(['spam', 'egg', 'spam', 'egg', 'python', 'egg'])

with open('wordfile.csv', 'w') as f:
    writer = csv.writer(f, delimiter=' ')
    writer.writerow(('word', 'count'))
    writer.writerows(counter.most_common())
Comments