Python 3 - count letters/words in text document/quick question

I'd like to know how to achieve the same result as the code I listed below without using any collections, or for someone to explain what goes on inside the Counter collection (in code or in a way that isn't confusing) since I can't seem to find it anywhere. This code is meant to read a text file called juliet.txt. I am trying to make it count the amount of letters and spaces inside the document and then print it as a result.

Code:

from collections import Counter
   text = open('juliet.txt', 'r').read()
   letters = 0
   counter = Counter(text)
   spacesAndNewlines = counter[' '] + counter['\n']

    while letters < len(text):
        print (text[letters])
        letters += 1
    while letters == len(text):
    print (letters)
    letters += 1
    print (spacesAndNewlines)

1 answer

  • answered 2019-03-14 08:27 dwagon

    Sounds like a homework question to me, in which case you won't get any benefit from me answering you.

    letters = {}
    with open('juliet.txt') as fh:
       data = fh.read()
    for char in data:
       if char in letters:
           letters[char] = 1
        else:
            letters[char] += 1
    print(letters)
    

    This uses a standard dictionary - normally I would use a defaultdict but for some weird reason you don't like collections. With the defaultdict you wouldn't need to do the laborious test to see if the char is already in the dictionary.