统计文件中每个字母的个数

关键点: 编写一个程序,提示用户输入一个文件名称,然后统计在不计大小写的情况下每个字符的出现次数。

解决思路:
1.将文件中的每一行作为字符串读取。
2.使用字符串的lower()函数将大写字符转换成小写。
3.创建含有26个整型值得名为counts 的列表,每个值是对每个字母出现次数的统计,比如 counts[1]统计的是‘b’出现的次数。
4.对于每个字符,判断其是否为小写字母(使用 isalpha()函数)。如果是,则将列表中的相应计数器加1.
5.最后,显示统计结果。
代码如下:

def main():
    filename = input("Enter a filename:").strip()
    infile = open(filename,"r")  #open the file

    counts = 26*[0]
    for line in infile:
        #Invoke the CountLetters function to count each letter
        countLetters(line.lower(),counts)

    for i in range(len(counts)):
        if counts[i] != 0:
            print(chr(ord('a')+ i) + " appears " + str(counts[i]) + (" time" if counts[i]==1 else " times"))
    infile.close()

#Count each letter in the string
def countLetters(line,counts):
    for ch in line:
        if ch.isalpha():
            counts[ord(ch) - ord('a')] += 1

main()
Enter a filename:input.txt
a appears 2 times
b appears 1 time
c appears 1 time
d appears 5 times
e appears 6 times
f appears 7 times
h appears 1 time
i appears 3 times
j appears 13 times
k appears 1 time
l appears 1 time
m appears 1 time
n appears 3 times
o appears 3 times
p appears 5 times
q appears 1 time
s appears 7 times
v appears 1 time
w appears 2 times
x appears 2 times
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值