Python 分别统计文章不同字符的数据
- 需求
- 定义不同的变量代表字符个数,然后根据自带的isX函数进行判断,符合就加1,不断循环即可
- 代码如下:
-
1 #coding:utf-8 2 #__author__ = 'Diva' 3 4 # func 5 def count_chars(text_input): 6 7 # 首先定义字符个数的变量 8 int_counts = 0 9 upper_counts = 0 10 lower_counts = 0 11 blank_counts = 0 12 other_counts = 0 13 14 # 用自带的isX函数来判断字符 15 for i in range(len(text_input)): 16 text_char = text_input[i] 17 if text_char.isupper(): 18 upper_counts += 1 19 elif text_char.islower(): 20 lower_counts += 1 21 elif text_char.isdigit(): 22 int_counts += 1 23 elif text_char.isspace(): 24 blank_counts += 1 25 else: 26 other_counts += 1 27 28 print(''' 29 不同字符的总数分别为: 30 upper_counts = %d, 31 lower_counts = %d, 32 int_counts = %d, 33 blank_counts = %d, 34 other_counts = %d ''' 35 % (upper_counts, lower_counts, int_counts, blank_counts, other_counts) 36 ) 37 38 # main 39 if __name__ == '__main__': 40 with open('aa.txt', 'r') as f: 41 text = f.read() 42 count_chars(text)
- 测试结果:
![]()
站在此岸链接彼岸,用高配版的自己,来带动低配版的自己。



浙公网安备 33010602011771号