Soccerninja Soccerninja - 29 days ago 5
Python Question

Defining file_counts

Re-implementation of the counts function that obtains a list of numbers from a
file. In the file, every single line will contain a single integer and nothing
else. The last character will be a newline.

filename :: a string indicating the name of a file in the current directory.

Return value: a dictionary of int as keys and # of occurrences as the values.

file_counts("file1.txt") → {100:3, 3:1, 9:2}

file_counts("file2.txt") → {1:1, 2:1, 3:1, 4:1, 5:1}


Test cases:

check that when file1.txt contains
"1\n1\n1\n2\n3\n3\n3\n3\n5\n"
, that
file_counts("file1.txt") == {1:3,2:1,3:4,5:1}
.

check that when file1.txt contains
"100\n100\n3\n100\n9\n9\n"
, that
file_counts("file1.txt") == {100:3, 3:1, 9:2}
.

Basically, the characters of the file will be printed on a new line the number of times they show up. So for 100:3, 100 would be printed 3 times.

*Background information:

def counts(xs):
d = {}
for item in xs:
d[item] = xs.count(item)
return d


This function counts the characters in the dictionary and returns the count of each character*

I am not sure how to implement this function. I have been trying multiple ways and this is the closest I have gotten to an answer. I am not sure what the missing piece/s is/are and would appreciate any help.

My code:

def file_counts(filename):
dict = {}
with open(filename) as file_counts:
for line in file_counts:


I get stuck on what to do next. I try to do an edit of the count function but it was not successful.

I am new to this site so I am not positive on format, so feel free to edit the question for formatting and if more information is required please ask

Answer

You can read in the whole document as a string with the read method. You will then have a string of values with \n characters in between each. You can reduce the string to a list of the values with the split() method. Finally, you can use the collections.Counter module to count the instances of each value.

import collections as c
def file_counts(filename):
    with open(filename, 'r') as f: # use flag 'r' to just read the doc
         data = f.read()      # read in the data file as a single string
    data = data.strip()       # get rid of the last \n on the end
    data = data.split('\n')   # break up the string into a list of values 
    counted_data = c.Counter(data)
    return dict(counted_data)

Note that you should avoid using dict to name you dictionary. dict is a reserved word in python used to generate a dictionary from a object which maps to a dictionary (eg - a list of tuples).