zoukankan      html  css  js  c++  java
  • 3333

    学号 2017****1016
    姓名 李双阳
    码云地址 https://gitee.com/LSY_IT/events

    程序分析,对程序中的四个函数做简要说明。要求附上每一段代码及对应的说明。

    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

    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

    def output_result(word_freq): (排序输出前10个次数单词)
    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": (调用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 -m cProfile word_freq.py Gone_with_the_wind.txt运行

    总共有3298次函数调用,程序总共耗时0.006秒

    执行次数最多的代码

    总结反思
    学习了词频统计这个程序,使我了解了性能分析,了解python这门语言。。

  • 相关阅读:
    JNI实例(含代码)
    sizeof()小结
    【转】C++ 关键字——friend
    curl资料小结
    【Curl (libcurl) 开发 之一】Cocos2dx之libcurl(curl_easy)的编程教程(帮助手册)!
    JSP中统一错误信息输出
    在号码池取连续号码的算法
    常用的文件操作方法
    走出基金净值的误区
    ResultSet概论
  • 原文地址:https://www.cnblogs.com/LSY-IT/p/10670300.html
Copyright © 2011-2022 走看看