对于查找统计字符,第一时间想到的是正则表达式,于是有了第一种实现
#coding=utf-8
import re
def classify_count(arg):
eng_letters=re.findall(r'[A-z]',arg)
chn_letters=re.findall(r'[\u4e00-\u9fa5]',arg)
table=re.findall(r'\s',arg)
figure=re.findall(r'\d',arg)
letters_num=len(eng_letters)+len(chn_letters)
table_num=len(table)
figure_num=len(figure)
other_num=len(arg)-letters_num-table_num-figure_num
print("字符串中字母个数为:{},空格个数为:{},数字个数为:{},其他字符个数为:{}".format(letters_num,table_num,figure_num,other_num))
if __name__ == '__main__':
classify_count("A中 国ui n23oj人ibs @Kf$fr*")
输出结果为:
字符串中字母个数为:16,空格个数为:3,数字个数为:2,其他字符个数为:3
后来又学习到python本身就提供了判断字符类型的方法,于是结合for循环,就更容易了
#coding=utf-8
def classify_count2(arg):
letters_num,table_num,figure_num,other_num=0,0,0,0
for i in arg:
if i.isalpha():
letters_num+=1
elif i.isdigit():
figure_num+=1
elif i.isspace():
table_num+=1
else:
other_num+=1
print("字符串中字母个数为:{},空格个数为:{},数字个数为:{},其他字符个数为:{}".format(letters_num,table_num,figure_num,other_num))
if __name__ == '__main__':
classify_count2("A中 国ui n23 oj人ibs @Kf$fr*")