第三次课后作业

本文介绍了一个简单的Python脚本,用于统计文本文件中单词出现的频率,并展示如何通过代码优化提升性能。通过使用标准库和命令行参数,该脚本能够方便地处理指定文件并输出最常见的十个单词。

学号:2017*****7154;   姓名:齐山   码云项目仓库:https://gitee.com/qishan66/project/tree/master

 

代码;

from string import punctuation def process_file(dst):3     try:         f = open(dst)     except IOError, s:         print s         return None     try:         bvffer = f.read()     except:         print "Read File Error!"         return None     f.close()     return bvffer

def process_buffer(bvffer):     if bvffer:         word_freq = {}         for item in bvffer.strip().split():             word = item.strip(punctuation+' ')             if word in word_freq.keys():                 word_freq[word] += 1             else:                 word_freq[word] = 1         return word_freq

def output_result(word_freq):     if word_freq:         sorted_word_freq = sorted(word_freq.items(), key=lambda v: v[1], reverse=True)         for item in sorted_word_freq[:10]:             print item

if __name__ == "__main__":     import argparse     parser = argparse.ArgumentParser()     parser.add_argument('dst')     args = parser.parse_args()     dst = args.dst     bvffer = process_file(dst)     word_freq = process_buffer(bvffer)     output_result(word_freq)

 

 

在命令中输入python word_freq.py Gone_with_the_wind.txt运行代码

使用cProfile进行性能分析 python -m cProfile word_freq.py Gone_with_the_wind.txt

修改代码if word in word_freq.keys()修改为if word in word_freq 再次分析

系统得到了优化 运行速度明显加快了很多。

转载于:https://www.cnblogs.com/qishan6666/p/10666638.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值