python之 heapq -- show me the code 0006
来源:互联网 发布:nginx 动静分离配置 编辑:程序博客网 时间:2024/04/27 18:40
题目要求统计出你每篇日记最重要的词。不太理解最重要的词是什么意思,所以把出现次数最多的单词弄出来了,
用到 heaqp 这种数据结构,heaqp 模块使用一个用对实现的优先级队列。 堆是一种简单的有序列表, 并且置入了堆的
相关规则。heapq模块有两个函数 nlargest(num,iteror,key) 和 nsmallest(num,iteror,key),方法返回可迭代对象中中最大(小)的
num个元素。参数key用于指定作为排序依据的键,默认为None。
<span style="font-size:14px;">nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]</span>
以上是关于 heaqp 的示例代码, 以下是小题目的代码:
__author__ = 'Administrator'# encoding=utf-8import heapqfrom collections import Counterdef mostly_important_word(file="youth.txt"): """第 0006 题:你有一个目录,放了你一个月的日记,都是 txt, 为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。""" data = [] with open(file) as handle: for line in handle: words = line.split() data.extend(words) dictionary = dict(Counter(data)) arr = [] for key in dictionary: temp = {"var": key, "count": dictionary[key]} arr.append(temp) word = heapq.nlargest(1, arr, key=lambda s: s["count"]) print("mostly important word is :", word[0]['var'])if __name__ == '__main__': mostly_important_word()
而且我相信,虽然代码很短,仍然有可优化的地方,只是我目前对 python 的了解程度还不够。 不管怎么说, 好好学习吧~
0 0
- python之 heapq -- show me the code 0006
- python 之 Counter ---show me the code 0004
- python之os -- show me the code 0005
- Show me the code之Python练习册 Q4~7
- Show me the code之Python练习册Q23-留言板
- python PIL --show me the code 0000
- python show-me-the-code 第0004
- Show me the code之Python练习册 Q1~3 优惠券
- Show me the code之Python练习册 Q8~9 html解析
- Show me the code之Python练习册 Q10 生成验证码
- Show me the code之Python练习册 Q11~12 关键词过滤
- Show me the code之Python练习册 Q13 获取网络图片
- Show me the code之Python练习册 Q14~16 excel操作
- Show me the code之Python练习册 Q17~19 xml操作
- python 操作 redis --show me the code 0003
- Python Show-Me-the-Code 第 0002 题 MySQL操作
- Python Show-Me-the-Code 第 0003 题 Redis操作
- Python Show-Me-the-Code 第 0004 题 统计单词
- SurfaceView实现动画
- Vim/Cscope 入门指导
- MVN的tomcat配置
- Android学习笔记十六.使用ContentProvider实现数据共享(二).URI...工具类
- leetcode----------------Median of Two Sorted Arrays
- python之 heapq -- show me the code 0006
- char* 和char[]的区别
- DIV+CSS简介
- 遍历对话框中的控件
- 数据结构课程设计 题目4
- iOS第三方开源库的吐槽和备忘 - 王培
- 算法竞赛入门经典(第2版)习题4-1 象棋UVa1589
- 进制转换
- 长沙土元养殖增加产量的四要点