计算字母在Python文本文件中出现的次数
在本文中,我们将学习计算字母在Python文本文件中出现的次数的不同方法。以下是我们将在以下程序中使用的文本文件gfg.txt的内容:
现在我们将讨论获取文本文件中字母出现频率的各种方法。
方法 1:使用内置的count()方法。
方法:
- 读取文件。
- 将文件的内容存储在变量中。
- 使用count()方法和参数作为需要频率的字母。
- 显示字母的计数。
执行:
Python3
# Program to get letter count in a text file
# explit 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 letetr count
print(letterFrequency('gfg.txt', 'g'))
Python3
# Program to get letter count in a text file
# explit 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'))
输出:
方法 2:遍历文件内容以将每个字符与给定的字母进行比较。
方法:
- 读取文件。
- 将文件的内容存储在变量中。
- 将计数器计数变量赋值为 0。
- 遍历每个字符,如果发现字符是给定的字母,则增加计数器。
- 显示字母的计数。
执行:
蟒蛇3
# Program to get letter count in a text file
# explit 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'))
输出: