In this article, you will learn how to calculate the frequency and percentage of a given letter in a text using Python.
Frequency and percentage 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.
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`.
- Q: How can I calculate the frequency of a different letter?
- A: You can simply change the letter that you are interested in counting. For example, to calculate the frequency of the letter `e`, you would change the `sign` variable to `e`.
- Q: How can I calculate the frequency of multiple letters?
- A: You can use a for loop to iterate over the letters that you are interested in counting.