字符串数量统计
from functools import reduce def count_alpha(str='', only_alpha=True): ''' 分类统计字符数量 :param str: 被统计字串。如:"hello world;" :param only_alpha: 只统计字母开关。True只统计字母,False只统计字母、数字、字符。 :return: 分类统计结果清单。如:[('h', 1), ('e', 1), ('l', 3), ('o', 2), ('w', 1), ('r', 1), ('d', 1), (';', 1)] ''' alpha_list = [] # 临时变量 alpha_count_list = [] # 存储统计结果 for ch in str1: # print(ch) if only_alpha: # 只统计字母 if ch.isalpha(): # 只统计字母 # print(ch) if ch not in alpha_list: alpha_list.append(ch) n = str1.count(ch) alpha_count_list.append((ch, n)) # print("%s: %s" % (ch, n)) else: # 只统计字母、数字、字符,不统计空格 if not ch.isspace(): # 只统计非空格 # print(ch) if ch not in alpha_list: alpha_list.append(ch) n = str1.count(ch) alpha_count_list.append((ch, n)) print("%s: %s" % (ch, n)) return alpha_count_list if __name__ == '__main__': str1 = "hello world;" r = count_alpha(str1, only_alpha=False) # 安照原有顺序排序 print(r) # 按照字母排序,a-z print(sorted(r, key=lambda x: x[0])) # 按照统计数量大小排序,由大到小 print(sorted(r, key=lambda x: x[1], reverse=True)) # 统计总数求和 sum = reduce(lambda x, y: [0, x[1] + y[1]], r)[1] print(sum)
输出:
h: 1
e: 1
l: 3
o: 2
w: 1
r: 1
d: 1
;: 1
[('h', 1), ('e', 1), ('l', 3), ('o', 2), ('w', 1), ('r', 1), ('d', 1), (';', 1)]
[(';', 1), ('d', 1), ('e', 1), ('h', 1), ('l', 3), ('o', 2), ('r', 1), ('w', 1)]
[('l', 3), ('o', 2), ('h', 1), ('e', 1), ('w', 1), ('r', 1), ('d', 1), (';', 1)]
11