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 of given letter

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


def frequency(txt, sign):
    counter: int = 0
    for s in txt:
        if s != sign:
            continue
        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  Image and Video Processing with OpenCV

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.

Frequency and percentage of given letter

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

def letter_stats(txt, sign):
    txt_lower = txt.lower()
    total_chars = len(txt_lower)
    counter: int = 0
    for s in txt_lower:
        if s == sign:
            counter += 1
    frequency = counter
    percentage = (frequency / total_chars) * 100 if total_chars > 0 else 0
    return frequency, percentage

frequency_c, percentage_c = letter_stats(text, 'c')
print(f'The frequency of "c" is: {frequency_c}')
print(f'The percentage of "c" is: {percentage_c:.2f}%')

The enhanced letter_stats function now calculates both the frequency and the percentage. First, it converts the input text to lowercase and calculates the total number of characters. Then, it iterates through the lowercase text, counting occurrences of the target character. Finally, it calculates the percentage by dividing the frequency by the total character count and multiplying by 100. The function returns both the frequency and the percentage, which are then printed to the console.

See also  How to convert char to string in Python

For robustness, consider adding error handling to your code. For instance, you might want to use a try…except block to handle potential FileNotFoundError if the text.txt file does not exist in the specified location. Furthermore, when opening files, it’s best practice to use a with open(…) as file: statement. This ensures that the file is automatically closed even if errors occur. For specifying file paths, especially if your script might run on different operating systems, using os.path.join() to construct file paths is recommended for platform independence.

See also  Leveraging Python's warnings Module for Debugging