0

How do you write a code that counts the number of occurrences a character has in a file and puts the data in a dictionary?

For example, If I supply the code to a file, I want it to return each new character as a key and the count as the value.

Let's say inside the file is python is cool

I want the code to return {'p':1, 'y':1, 't':1, 'h':1, 'o':3 ...}

I understand how to count the characters in a string by simply using:

def count_chars(text):
    '''
    (string) -> int
    Returns the length of text.

    Examples:
    >>> count_chars("simon")
    5
    >>> count_chars("")
    0
    '''
    count = 0
    for ch in text:
        count += 1
    return count

However, I'm struggling with how to open the file and then put the data into a dictionary.

Hoai Nam
  • 45
  • 10
Simon Ayalew
  • 3
  • 1
  • 2
  • Does this answer your question? [Find count of characters within the string in Python](https://stackoverflow.com/questions/40950905/find-count-of-characters-within-the-string-in-python) – Hoai Nam Sep 03 '22 at 15:34

3 Answers3

4

Since you've mentioned that this is for an assignment, I thought I'd show you how this is done more 'directly' using a dictionary / without using Counter, so you actually understand what's going on under the hood.

d = {}    # initialise a dictionary
with open(file_path, 'r') as f:    # open the file, call it 'f'
    for line in f:    # read through each line in the file
        for c in line:    # read through each character in that line
            if c in d:    # check if character is in dictionary
                d[c] += 1     # if it's been seen before, increment counter
            else:
                d[c] = 1    # otherwise, insert it into the dictionary
Deem
  • 7,007
  • 2
  • 19
  • 23
  • Thank you, this makes a lot more sense. The assignment required me to write other functions to count words, and certain lines.. I was able to refer to this to write the other codes. This was a lot of help! – Simon Ayalew Aug 08 '18 at 03:35
  • Glad it helped. Please click the green tick on the left if this was the answer you were looking for! Also, just for the future, try splitting your questions into smaller parts - for example, you would be able to find existing answers on 'how to read string from file' and 'how to count letters from string using dictionary' quite easily on this site. Good luck with your learning! – Deem Aug 08 '18 at 06:53
2

Use the included collections.Counter class. The most_common method even includes a code sample being used to count the characters of a string:

>>> Counter('abracadabra').most_common(3)  
[('a', 5), ('r', 2), ('b', 2)]

Putting that together with opening a file:

from collections import Counter
def count_characters(source_file_name):
    with open(source_file_name, 'r') as source_file:
        return Counter(source_file.read())
Alex Taylor
  • 8,343
  • 4
  • 25
  • 40
  • Hello Alex, Thanks for the response. one of the restrictions of my assignment is that the return value cannot be a list or tuple.. The code has to strictly return a dictionary with the char as the key and the count as the value. My apologies if that was not clear in the question.. – Simon Ayalew Aug 08 '18 at 01:37
0

To meet your project requirements simply convert Counter to dict. From Alex's code:

from collections import Counter
def count_characters(source_file_name):
    with open(source_file_name, 'r') as source_file:
        return dict(Counter(source_file.read()))
modelbuilder42
  • 319
  • 4
  • 5