python - Create a csv file with two columns | Counter mode -
i worked on code counting occurrencies of words in given text document , save output on csv file 2 columns: 1 words , 1 frequencies.
this code trying replicate:
from collections import counter counter = counter(['spam', 'egg', 'spam', 'egg', 'python', 'egg']) open('wordfile.csv', 'w') f: writer = csv.writer(f, delimiter=' ') writer.writerow(('word', 'count')) writer.writerows(counter.most_common())
however, output:
word countegg 3spam 2python 1
the output trying should contain 2 columns (one "word" adn 1 "frequency" , each row should contain word , occurrance in text:
word, frequency, the, 3165, in, 1265, of,1233,
when print output 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 can see there aren't 2 columns word , frequency. using windows , python version using: 3.5.2 |anaconda 4.1.1 (64-bit)
writer.writerow
expecting list of columns row; in snippet passing results ie. columns of items.
you need iter on counter.items()
result want:
import csv collections import counter counter = counter(['spam', 'egg', 'spam', 'egg', 'python', 'egg']) open('wordfile.csv', 'w', newline='') f: writer = csv.writer(f, delimiter=' ') writer.writerow(('word', 'count')) writer.writerows(counter.most_common())
Comments
Post a Comment