I know of one more wonderful way to play with text using Python. It is a good way to learn the Python language. We will calculate a percentage in a python. The exact task is to count the frequency of a given letter in the text.
Count letters
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'))
I created a sample text.txt file. I used the famous Lorem Ipsum text 😉
Next I opened the file in read mode. It is the default mode, but I put it on for you for better visibility. Then I read the file and closed it to free up the memory.
My frequency function is iterating the text. The counter increases every time a given letter occurs.
In the end, I printed the output out. I used the lower function, so both lowercase C and uppercase C will be counted.
Bonus!
How to calculate percentage in python?
print('letter','occurence','precent') for s in 'abcdefghijklmnopqrstuvwxyz': howMany = frequency(text.lower(), s) percent = 100 * howMany / len(text) print('{0} - {1} - {2}%'.format(s.upper(), howMany, round(percent, 1)))
For fun, I have also created a code that counts the percentage of letters in the text.
I iterate again. Count the length of the text. Then the percentage is multiplied by 100. And finally, print this out rounded to the one digit after the comma.
That’s how you calculate both the frequency and percentage of letters in the text. I hope it was fun for you, just like it was for me 😉