首页 > 其他 > 详细

软工作业 3:个人编程

时间:2018-10-06 18:51:14      阅读:183      评论:0      收藏:0      [点我收藏+]

一、程序分析

def process_file(dst):     # 读文件到缓冲区
    try:     # 打开文件
        f=open(dst,‘r‘)
    except IOError as s:
        print (s)
        return None
    try:     # 读文件到缓冲区
        x=f.read()
    except:
        print ("Read File Error!")
        return None
    bvffer=x
    return bvffer

 def process_buffer(bvffer):
    if bvffer:
        word_freq = {}                     #新建一个空字典word_freq
        # 下面添加处理缓冲区 bvffer代码,统计每个单词的频率,存放在字典word_freq
        for word in bvffer.split():      #.split()函数将bvffer切片
            if word not in word_freq:
                word_freq[word]=0
            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]:  # 输出 Top 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)

二、代码风格说明

if/for/while一定要换行

例如:

if bvffer:
        word_freq = {}          

三、程序运行命令、运行结果截图

技术分享图片

 技术分享图片

四、性能分析结果及改进

执行时间最多的代码:

技术分享图片

 

执行次数最多的代码:

技术分享图片

 

软工作业 3:个人编程

原文:https://www.cnblogs.com/uiki007/p/9748035.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!