msprague
msprague

Reputation: 11

Use a file as an argument for a function that counts creates a count for each letter in a text file

My program right now works for only the first character in the text file, and iterates infinitely. For example if the first letter in the text file is d, the program returns {'d': 1} over and over again.

I need it to continue through the text file and count each letter and ultimately to list the letter counts in decreasing order.

def add_or_init(dictionary, c):
    if(c in dictionary):
            dictionary[c]+=1
    else:
            dictionary[c]=1
def count_one_letter(dictionary, c, is_letter):
    if is_letter(c):
            add_or_init(dictionary, c)
def count_letters(dictionary, word, is_letter):
    f = open('suffix.txt')
    for word in f.read().split():
        for c in word:
            count_one_letter(dictionary, c, is_letter)
            return dictionary
f = open('suffix.txt')
for word in f.read().split():
t=len(word)
while True:
    print(count_letters(dict(),word,lambda x: True))

Upvotes: 1

Views: 37

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 60944

If you can, use Counter from collections

from collections import defaultdict, Counter
with open('filename.txt') as f:
    text = f.read()
    letter_count = Counter(c for c in text if c.isalpha())

Then to print in decreasing order:

print(letter_count.most_common())

Upvotes: 1

Related Questions