首页 › Python 实例 › 统计字符出现次数

Python 统计字符出现次数

字符串实例 020

题目

统计一段文字中每个字符(以及每个单词)出现的次数,输出最常见的几个。

参考代码

from collections import Counter

text = "Python is easy to learn. Python is powerful. Learn Python today!"

chars = Counter(ch.lower() for ch in text if ch.isalpha())
print("最常见的 5 个字母:", chars.most_common(5))

words = Counter(w.strip(".!").lower() for w in text.split())
print("最常见的 3 个单词:", words.most_common(3))
执行以上代码输出结果为:
最常见的 5 个字母: [('o', 6), ('y', 5), ('t', 5), ('n', 5), ('p', 4)]
最常见的 3 个单词: [('python', 3), ('is', 2), ('learn', 2)]

代码解析

Counter 接收任意可迭代对象并统计每个元素出现的次数,most_common(n) 返回出现次数最多的 n 个元素。