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

来源:互联网 发布:一般美工培训班多少钱 编辑:程序博客网 时间:2024/05/16 07:44

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

解决思路:
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 stringdef countLetters(line,counts):    for ch in line:        if ch.isalpha():            counts[ord(ch) - ord('a')] += 1main()
Enter a filename:input.txta appears 2 timesb appears 1 timec appears 1 timed appears 5 timese appears 6 timesf appears 7 timesh appears 1 timei appears 3 timesj appears 13 timesk appears 1 timel appears 1 timem appears 1 timen appears 3 timeso appears 3 timesp appears 5 timesq appears 1 times appears 7 timesv appears 1 timew appears 2 timesx appears 2 times
原创粉丝点击