关键点: 编写一个程序,提示用户输入一个文件名称,然后统计在不计大小写的情况下每个字符的出现次数。
解决思路:
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