Python练手项目0006
来源:互联网 发布:网络购物英文翻译 编辑:程序博客网 时间:2024/04/29 16:11
本项目采用的是https://github.com/Yixiaohan/show-me-the-code中所提供的练习项目,所有代码均为原创,转载请注明,谢谢。
问题描述:练习0006的问题是有一个txt文本,里面有一些话,需要检索出里面每个词出现的频率,从而找出出现频率最高的关键词。
具体代码如下:
"""
Created on Wed Jan 04 13:58:39 2017
@author: sky
"""
"""
第 0006 题:你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。
"""
import re
def import_word(target_file):
file_object = open(target_file,'r')
file_content = file_object.read()
p = re.compile(r'[\W\d]*')
word_list = p.split(file_content)
word_dict = {}
for word in word_list:
if word not in word_dict:
word_dict[word] = 1
else:
word_dict[word] += 1
sort = sorted(word_dict.items(),key=lambda e :e[1],reverse=True)
file = open('result.txt','w')
file.write(str(word_dict))
file.close()
print "the most word in '%s' is '%s', it appears %s times" % (target_file, sort[0][0],sort[0][1])
file_object.close()
if __name__ == "__main__":
import_word('1.txt')
注意:
{}的作用是生成一个dict,而字典本身没有write的属性,所以需要自己建立一个txt文本,然后将dict 转化成str,才能存储
详细代码和结果,可以参考https://github.com/g8015108/exercise-for-python
- Python练手项目0006
- python练手项目0005
- python练手项目0007
- Python练手项目0008
- Python练手项目0009
- Python练手项目0010
- Python练手项目0011
- Python练手项目0012
- Python练手项目0013
- Python练手项目
- Python练手项目0014
- Python练手项目0015
- Python练手项目0016
- python练手小项目
- 10个Python练手项目
- 10个python练手项目
- 【Python】 Flask 缘分匹配练手项目
- Python练手项目(来源于知乎)
- CENTOS 6.5 配置YUM安装NGINX
- UA 判断 手机OS
- 画板UI实现
- 在navicat上设置定时计划执行存储过程
- 服务端基本步骤+客户端基本步骤+(协议层+传输层+服务端)类型
- Python练手项目0006
- Win7遇到:应用程序已停止工作,故障模块 ntdll.dll
- office 快捷键
- 闭包
- 【Microsoft】Project Oxford
- usb-descriptor(三)
- nodejs+webpack的安装
- 安卓加载中对话框
- Go学习笔记六(并发编程)