Count the number of times a letter appears in a text file in Python
In this article, we will be learning different approaches to count the number of times a letter appears in a text file in Python. Below is the content of the text file gfg.txt that we are going to use in the below programs:
Now we will discuss various approaches to get the frequency of a letter in a text file.
Method 1: Using the in-built count() method.
Approach:
- Read the file.
- Store the content of the file in a variable.
- Use the count() method with the argument as a letter whose frequency is required.
- Display the count of the letter.
Implementation:
Python3
# Program to get letter count in a text file # explicit function to return the letter count def letterFrequency(fileName, letter): # open file in read mode file = open (fileName, 'r' ) # store content of the file in a variable text = file .read() # using count() return text.count(letter) # call the function and display the letter count print (letterFrequency( 'gfg.txt' , 'g' )) |
Output:
Method 2: Iterate through the file content in order to compare each character with the given letter.
Approach:
- Read the file.
- Store the content of the file in a variable.
- Assign a counter count variable with 0.
- Iterate through each character, if the character is found to be the given letter then increment the counter.
- Display the count of the letter.
Implementation:
Python3
# Program to get letter count in a text file # explicit function to return the letter count def letterFrequency(fileName, letter): # open file in read mode file = open (fileName, "r" ) # store content of the file in a variable text = file .read() # declare count variable count = 0 # iterate through each character for char in text: # compare each character with # the given letter if char = = letter: count + = 1 # return letter count return count # call function and display the letter count print (letterFrequency( 'gfg.txt' , 'g' )) |
Output: