1) 自己的基本信息:

  • 学号:2017*****1041;
  • 姓名:郎华
  • 码云仓库地址:https://gitee.com/langhua0310/word_frequency

2) 程序分析

  • 读取文件到缓冲区
def process_file(dst):     # 读文件到缓冲区
    try:     # 打开文件
        f = open(dst)
    except IOError as s:
        print (s)
        return None
    try:     # 读文件到缓冲区
        bvffer = f.read()
    except:
        print ("Read File Error!")
        return None
    f.close()
    return bvffer
  •  添加处理缓冲区 bvffer代码,统计每个单词的频率,存放在字典word_freq
def process_buffer(bvffer):
    if bvffer:
        word_freq = {}
        # 下面添加处理缓冲区 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
  • 设置输出函数,排序并输出 Top 10 的单词,统计词频
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)
  • 调用main函数,用来测试
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)

3) 性能分析结果及改进。

  •  Gone_with_the_wind.txt运行:

  • Gone_with_the_wind.txt 执行次数最多的代码:

 

  • Gone_with_the_wind.txt 执行时间最长的代码:

 

 4)改进代码及结果截图 。

代码改进后缩短了执行时间

def process_buffer(bvffer):

函数中的代码

if word in word_freq.keys():

改为

if word in word_freq:
  • 运行结果

 

 

 

 5) 给出你对此次任务的总结与反思。

在本次课后作业中,我更加熟练的掌握了码云以及博客云的使用,也再一次复习了上次作业中git传输远程仓库的操作。学会了新建分支。

posted on 2019-04-08 14:50  郎华  阅读(177)  评论(3编辑  收藏  举报