python - CSV to text file layout -


i outputting 2 columns of csv file text file , printing on single line in text file. this:

product name counter({'descriptions': 1, 'descriptions':3}) 

but want print out this:

product name counter({'descriptions': 1,                        'descriptions': 3}) 

here code have far:

import csv   import sys  collections import defaultdict  collections import counter  data = defaultdict(list)   class dictionary:      open ('practice.csv', 'rb') f:         reader = csv.reader(f)         next(reader, none)          row in reader:             data[row[2]].append(row[3])        text_file = open("test.txt", "w")     data_count = counter()     key in data.keys():           sys.stdout = text_file          print key, counter(data[key])     text_file.close() 

how can text file not print out on 1 line? not sure how work.

the counter({'descriptions': 1, 'descriptions':3}) stuff output of counter's __str__() function. when use print counter(stuff), implicitely called new object generated counter(stuff). if understand correctly, want reformat output.

you storing output of counter(data[key]) in variable , modify output adding newlines @ positions of , in output:

a = str(counter(data[key])) print '\n'.join(a.split(',')) 

which quite ugly ;-)

you could, however, design ouptut yourself: keys of counter accessible via a.keys(), add loop:

a = counter(data[key]) print key, 'counter({', counter_key in a.keys():     print counter_key + ': ' + a[counter_key] + ',' print '})' 

which iterates on content of counter , outputs key-value combination counter line line.

edit: second part of code this:

text_file = open("test.txt", "w") key in data.keys():     text_file.writelines(key + ' counter({')     counted = counter(data[key])     counter_key in counted.keys():         text_file.writelines('  ' + counter_key + ': ' + counted[counter_key] + '\n')     text_file.writelines('})\n') text_file.close() 

note: it's possible iterate on key/value pairs in counter using

for counter_key, counter_value in counted.items(): 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -