1. 程式人生 > >軟工作業三:對輸入文件的詞頻統計

軟工作業三:對輸入文件的詞頻統計

包括 asc filename pro ava ext 符號 function width

一、程序分析

  (1)、讀文件到緩沖區

def process_file(dst):           #讀文件到緩沖區
    try:                         #打開文件
       txt = open(dst,r)       #dst為文本目錄路徑
    except IOError as s:
        print(s)
        return None
    try:                         #讀文件到緩沖區
        bvffer = txt.read()
    except:
        
print("Read File Error!!") return None txt.close() return bvffer

(2)、處理緩沖區代碼,統計每個單詞的頻率,存放在字典中

def process_buffer(bvffer):
    if bvffer:
       word_freq = {}
       #下面添加處理緩沖區bvffer代碼,統計每個單詞的頻率,存放在word_freq
       bvffer = bvffer.lower()
       for ch in “‘!;,.?”
: # 除去文本中的中英文標點符號 bvffer = bvffer.replace(ch, " ") words = bvffer.strip().split() for word in words: word_freq[word] = word_freq.get(word, 0) + 1 return word_freq

(3)、設置輸出函數,輸入詞頻數量排序結果

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("詞:%-5s 頻:%-4d " % (item[0], item[1]))

(4)、主函數

def main():
    dst =‘F:/軟件工程/word_freq/Gone_with_the_wind.txt  # 《飄》文件的路徑
    bvffer = process_file(dst)
    word_freq = process_buffer(bvffer)
    output_result(word_freq)

二、代碼風格說明

(1)縮進

Python語言對代碼之間的縮進表達代碼之間的包括與層次關系,要求嚴格明確 ,格式為四個空格。

習慣C語言的人容易在這點上犯錯,會出現語法錯誤:

IndentationError: unindent does not match any outer indentation level

三、程序運行結果截圖

技術分享圖片

四、性能分析結果及改進

(1)、執行次數最多

結果表明代碼 word_freq[word] = word_freq.get(word, 0) + 1 執行次數最多

技術分享圖片

(2)、執行時間最長

技術分享圖片

(3)、查看三個函數分別調用了哪些函數

技術分享圖片

註:ncalls:表示函數調用的次數;
tottime:表示指定函數的總的運行時間,除掉函數中調用子函數的運行時間;
percall:(第一個percall)等於 tottime/ncalls;
cumtime:表示該函數及其所有子函數的調用運行的時間,即函數開始調用到返回的時間;
percall:(第二個percall)即函數運行一次的平均時間,等於 cumtime/ncalls;
filename:lineno(function):每個函數調用的具體信息;

(4)、可視化操作

  • 需要安裝:graphviz 到官網下載graphviz-2.38.zip
  • 下載gprof2dot.py

  • 執行下述步驟:

    1.  進行性能分析;分析結果保存到 result 文件,cProfile.run("main()", "result");
    2.  轉換為圖形; 將 result文件 轉換為 png 圖形格式。 命令:python gprof2dot.py -f pstats result | dot -Tpng -o result.png
  • 轉換得到圖形如下:

技術分享圖片

軟工作業三:對輸入文件的詞頻統計