Frequency and percentage of given letter in the text

You will learn how to calculate the frequency and percentage of a given letter in a text using Python.

frequency percentage

Frequency and percentage of given letter

file = open('text.txt', 'r')
text: str =

def frequency(txt, sign):
    counter: int = 0
    for s in txt:
        if s != sign:
        counter += 1
    return counter

print('The frequency is ', frequency(text.lower(), 'c'))

The first line opens the text file in read mode. The second line reads the text from the file and stores it in the text variable. The third line closes the file to free up the memory.

See also  How To Remove n From String In Python?

The frequency function iterates over the text and counts the number of times the given letter appears. The counter variable is incremented every time the letter is found.

The last line prints the frequency of the letter c.