标题: [转载教程] Python统计出文本中出现次数最多的一个字符 [打印本页]
作者: 依山居 时间: 2015-10-21 19:35 标题: Python统计出文本中出现次数最多的一个字符
原贴:批处理如何统计出文本中出现次数最多的一个字符?
http://www.bathome.net/thread-37725-1-1.html
搜索到python Counter这个神器:
http://www.zlovezl.cn/articles/collections-in-python/- # -*- coding: utf-8 -*-
- """
- 下面这个例子就是使用Counter模块统计一段句子里面所有字符出现次数
- """
- from collections import Counter
-
- s = '''A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.'''.lower()
-
- c = Counter(s)
- # 获取出现频率最高的5个字符
- print c.most_common(5)
-
-
- # Result:
- [(' ', 54), ('e', 32), ('s', 25), ('a', 24), ('t', 24)]
复制代码
欢迎光临 批处理之家 (http://bbs.bathome.net/) |
Powered by Discuz! 7.2 |