1. 程式人生 > >軟工作業:詞頻統計

軟工作業:詞頻統計

oerr eve png 之前 call urn 程序代碼 int http

一、程序分析

(1)讀文件到緩沖區 process_file(dst)

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

2統計緩沖區的裏每個單詞的頻率,放入 process_buffer(bvffer)

def process_buffer(bvffer):
    if bvffer:
        word_freq = {}
        # 下面添加處理緩沖區 bvffer代碼,統計每個單詞的頻率,存放在字典word_freq
        for ch in “‘!;,.?”: #把換行都換為空
            bvffer = bvffer.lower().replace(ch, " ")
        words = bvffer.strip().split()
        
for word in words: word_freq[word] = word_freq.get(word, 0) + 1 #給單詞計數 return word_freq

(3)輸出詞頻前十的單詞 output_result(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)

(4)主函數對之前的函數進行整合

if __name__ == "__main__":
    path =  "E:\Gone_with_the_wind.txt"
    bvffer = process_file(path)
    word_freq = process_buffer(bvffer)
    output_result(word_freq)

二、代碼風格說明

python代碼在每行末尾不用加“;”

例如:

path =  "E:\Gone_with_the_wind.txt"
    bvffer = process_file(path)
    word_freq = process_buffer(bvffer)
    output_result(word_freq)

三、程序運行命令、運行結果截圖

技術分享圖片

四、性能分析結果及改進

(1)執行時間最多的代碼

技術分享圖片

(2)執行次數最多的代碼

技術分享圖片

(3)嘗試改進程序代碼

減少運行時間:減少耗時最長的代碼的運行時間

        for ch in “‘!;,.?”:
            bvffer = bvffer.replace(ch, " ")

改為

     bvffer = bvffer.lower()
         for ch in “‘!;,.?”:
            bvffer = bvffer.replace(ch, " ")

可視化操作

根據運行次數排序方式分析命令

python -m cProfile -o resultc.out -s call test3.py

python gprof2dot.py -f pstats result.out | dot -Tpng -o result.png

技術分享圖片

根據占用時間排序方式分析命令

python -m cProfile -o result.out -s cumulative test3.py

python gprof2dot.py -f pstats result.out | dot -Tpng -o result.png

技術分享圖片

軟工作業:詞頻統計