请看一下这道Python程序!

怎么用Python统计文本文件中的各类字符个数啊,实在是不会,统计数字,字母及其他字符的个数。
有谁会吗,指点指点我吧!运行结果大概这样

img

读取文本文件内容,转换成列表,然后列表循环计数统计?

img


import string

 

s = '123runoobc  kdf235*(dfl'
 

letters = 0
 

space = 0
 

digit = 0
 

others = 0
 

for c in s:
 

   if c.isalpha():
 

       letters += 1
 

   elif c.isspace():
 

       space += 1
 

   elif c.isdigit():
 

       digit += 1
 

   else:
 

       others += 1
 

print ('char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others))
cnum = 0
cstr = 0
cel = 0
with open('test.txt', 'r') as f1:
    for i in f1.read().strip().replace('\n',''):
        if i <='9' and i >= '0':
            cnum += 1
        elif (i <= 'z' and i >= 'a') or (i <= 'Z' and i >= 'A'):
            cstr += 1
        else:
            cel += 1
print('字母有{}个,数字有{}个,其他字符有{}个'.format(cstr, cnum, cel))

第一行中的文件名 'test.txt' 请按实际的改:

with open('test.txt','r') as f:
    data = f.read()

letters = numbers = others = 0
for c in data:
    if c.isalpha():
        letters += 1
    elif c.isdigit():
        numbers += 1
    else:
        others += 1

print(f'字母有{letters}个,数字有{numbers}个,其他字符有{others}个')