Question

The function prints out the individual frequency for letters in a file but I cant get it to ignore non letters, I only want it to count letters when working out the percentage frequency of each letter. This what I have so far:

from string import ascii_lowercase as lowercase

def calcFrequencies(file):
    """Enter file name in quotations. Shows the frequency of letters in a file"""
    infile = open(file)
    text = infile.read()
    text = text.lower()

    text_length = len(text)
    counts = [0]*26

    for i in range(26):
        char=lowercase[i]
        counts[i] = 100*text.count(char)/text_length
        print("{:.1f}% of the characters are '{}'".format(counts[i],char))
    infile.close()
Was it helpful?

Solution 2

You could use the join method with a list comprehension (faster than a genexp) to reassign the string with only the alphabetic characters before counting:

text = ''.join([char for char in text if char.isalpha()])

OTHER TIPS

Use filter

>>> text = "abcd1234efg"
>>> filter(str.isalpha, text)
'abcdefg'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top