[Tutor] Help with loops

Joel Goldstick joel.goldstick at gmail.com
Tue Jan 5 14:13:51 EST 2016


On Tue, Jan 5, 2016 at 12:27 PM, Chelsea G <cegarcia0323 at gmail.com> wrote:

> I need to create a loop to print out the most common phrases with the
> counts 5 or greater and the rest to be bucketed into other category. How do
> I write the loop to print out the common phrases that have counts of 5 or
> more? This is my code so far:
>

Can you explain what you mean by common phrases with a count of 5 or more?
Show some same input file data here to better explain your assignment.

>
> import csv#from sys import argvfrom collections import defaultdictfrom
> collections import Counter#script, filename = argv
> data = defaultdict(list)
> class dictionary:
>
I think this looks like function code -- not a class

>     with open ('practice.csv', 'rb') as f:
>        reader = csv.reader(f)
>        #text_file = open("output.txt", "w")
>        next(reader, None)
>        for row in reader:
>           data[row[2]].append(row[3])
>
> why is row[2] and row[3] the only data you want to collect?  You defined
data outside of your function -- not good.

>        #text_file.write("%r" % data)
>
>        #text_file.close()
>
>    #print(data)
>
>    text_file = open("count.txt", "w")
>    data_count = Counter()
>    for d in data.values():
>       data_count += Counter(d)
>    print data_count.most_common(5)
>    text_file.write("%r" % data_count.most_common(5))
>    text_file.close()
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

This code is quite a mess.  That's ok.  Try to write code to just read the
file first.  Work from there

-- 
Joel Goldstick
http://joelgoldstick.com:8000/stats/birthdays
<http://joelgoldstick.com/stats/birthdays>


More information about the Tutor mailing list