[Tutor] Help!

Chelsea G cegarcia0323 at gmail.com
Fri Jan 15 11:33:24 EST 2016


Hi,
So what I am working on is taking a csv file and only taking 2 columns from
the spreadsheet and out putting that to a text file. Then taking those two
columns and organize them by product(key) and outputting the
description(values) that are associated. Some products have a lot of
duplicate descriptions and I am trying to get the counts of those. I have a
piece of code that takes anything greater then 5 and prints that and also
anything 4 or less goes into an 'other' category with the counts.So what I
am trying to do now is import a csv and change it to a text file with the
same naming convention as the csv. Below is my functions code:

import csv
import json
import sys
from collections import defaultdict
from collections import Counter

class dictionary():
def __init__(self, filename):
self.dict = defaultdict(list)
self.counted_dict = defaultdict(list)
self.grouped_dict = defaultdict(list)
self.other_dict = defaultdict(list)
self.final_dict = defaultdict(list)
self.total_dict = defaultdict(list)
self.txt_output = " "
def populate_dict(self, filename):
with open (filename, 'rb') as f:
reader = csv.reader(f)
next(reader, None)
for row in reader:
self.dict[row[2]].append(row[3])
def total_counts(self):
for key in self.dict.keys():
total = 0
b = Counter(self.dict[key])
for value in b:
total += b[value]
self.total_dict.update({key: str(total)})
def all_counts(self):
data_count = Counter()
for key in self.dict.keys():
self.counted_dict.update({key: Counter(self.dict[key])})
def grouped_counts(self):
for key in self.dict.keys():
total = 0
c = Counter(self.dict[key])
for value in c:
if c[value] >= 5:
self.grouped_dict.update({value: key + ': ' + str(c[value])})
elif c[value] <= 4:
total += c[value]
self.other_dict.update({key: 'other: ' + str(total)})
self.final_dict = self.grouped_dict, self.other_dict, self.total_dict,
def txt_output(self, filename):
a = filename.split('.')
self.txt_output = a + '.txt'
print a
def json_output(self):
with open (self.txt_output.txt, 'w') as text_file:
json.dump(self.final_dict, text_file, sort_keys = True, indent = 4)



What I am having issues with is the def txt_output that is where I am
trying to take the .csv off and add the .txt but keep the filename the
same. For example, having a filename "weekly_20160102.csv" and then create
a txt filename with "weekly_20160102.txt" and have all the counts and
products in the text file. Is there any way to do this?


More information about the Tutor mailing list