使用Python 统计高频字数的方法
2019-02-15 00:21
1026 查看
问题
(来自Udacity机器学习工程师纳米学位预览课程)
用 Python 实现函数 count_words(),该函数输入字符串 s 和数字 n,返回 s 中 n 个出现频率最高的单词。返回值是一个元组列表,包含出现次数最高的 n 个单词及其次数,即 [(<单词1>, <次数1>), (<单词2>, <次数2>), ... ],按出现次数降序排列。
可以假设所有输入都是小写形式,并且不含标点符号或其他字符(只包含字母和单个空格)。如果出现次数相同,则按字母顺序排列。
例如:
print count_words("betty bought a bit of butter but the butter was bitter",3)
输出
[('butter', 2), ('a', 1), ('betty', 1)]
解法
"""Count words.""" def count_words(s, n): """Return the n most frequently occuring words in s.""" w = {} sp = s.split() # TODO: Count the number of occurences of each word in s for i in sp: if i not in w: w[i] = 1 else: w[i] += 1 # TODO: Sort the occurences in descending order (alphabetically in case of ties) top = sorted(w.items(), key=lambda item:(-item[1], item[0])) top_n = top[:n] # TODO: Return the top n most frequent words. return top_n def test_run(): """Test count_words() with some inputs.""" print count_words("cat bat mat cat bat cat", 3) print count_words("betty bought a bit of butter but the butter was bitter", 3) if __name__ == '__main__': test_run()
小结
主要两个小技巧:
用split()将输入字符串按空格分开;
用sorted()函数对字典 先按值,再按键 进行排序,尤其是item:(-item[1], item[0])) 代表先对item的第二个元素 降序 排列(item 之前用了-),然后对第一个元素 升序 排列。多个元素的元组亦然。
以上这篇使用Python 统计高频字数的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章推荐
- Python中使用Counter进行字典创建以及key数量统计的方法
- Python开发的单词频率统计工具wordsworth使用方法
- Python实现统计文本文件字数的方法
- 用 Python 统计高频字数
- Python开发的单词频率统计工具wordsworth使用方法
- 【用Python写爬虫】获取html的方法【一】:使用urllib
- Python 中的strip lstrip rstrip使用方法 .
- 【用Python写爬虫】获取html的方法【三】:使用cPAMIE
- 【原】Python/C API使用方法简介 (在C/C++中嵌入Python)
- Python strip lstrip rstrip使用方法(字符串处理空格)
- 【python】【scrapy】使用方法概要(四)
- python下使用qrcode方法
- python中datetime的比较方法使用
- 使用python获取本地时区的几种方法
- Python中使用中文的方法
- ArcMap中使用Python遇到中文字段名错误的解决方法
- Python optionParser模块的使用方法
- python join 和 split的常用使用方法
- Python中条件选择和循环语句使用方法介绍
- Python __getattr__与__setattr__使用方法