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.