Python - 统计字符串中不区分大小写的字母数量
我想要找出一个字符串中每个字母出现的次数,忽略大小写、空格和特殊字符。有什么好的方法吗?
比如:
i/p: ABCccCDde :)! f
o/p: A=1, B=1, C=4, D=2, E=1
我试过
abc = Counter(line.rstrip('\n'))
还有用过 defaultdict
,但是它们没有忽略大小写。而且我还需要快速去掉特殊字符,不想花太多时间。
1 个回答
7
试试看
>>> abc = 'ABCccCDde :)! f'
>>> from collections import Counter
>>> Counter(c for c in abc.upper() if c.isalpha())
Counter({'C': 4, 'D': 2, 'A': 1, 'B': 1, 'E': 1, 'F': 1})