1. 程式人生 > >軟工作業 3:個人編程練習

軟工作業 3:個人編程練習

call pre tps items ati put 程序 及其 排序

一、程序分析

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

2、處理緩沖區,統計每個單詞的頻率,存放在字典word_freq
def process_buffer(bvffer):
if bvffer:
word_freq = {} # 下面添加處理緩沖區 bvffer代碼,統計每個單詞的頻率,存放在字典word_freq
bvffer = bvffer.lower() # 把文本中大寫字母轉換為小寫
for ch in ‘!"#$%&()*+-,-./:;<=>?@“”[\\]^_{|}~‘: # 除去文本中的中英文標點符號並將文本內容改為小寫
bvffer = bvffer.replace(ch, " ")
words = bvffer.split() # 分割字符串
for word in words:
word_freq[word] = word_freq.get(word, 0) + 1
return word_freq

3、輸出 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("{0:<10}{1:>5}".format(item[0], item[1]))

4、創建一個main函數,進行文本測試
def main():

dst = ‘Gone_with_the_wind.txt‘
bvffer = process_file(dst)
word_freq = process_buffer(bvffer)
output_result(word_freq)


5、添加進主函數,統計並評估該詞頻
if __name__ == "__main__":
import cProfile
import pstats
cProfile.run("main()", filename="result.out") # 把分析結果保存到文件中,增加排序方式
p = pstats.Stats(‘result.out‘) # 創建Stats對象
p.sort_stats(‘calls‘).print_stats(10) # 按照調用次數排序,打印前10函數的信息
p.strip_dirs().sort_stats("cumulative", "name").print_stats(10) # 按照運行時間和函數名排序,只打印前10行函數的信息
p.print_callers(0.5, "process_file") # 想知道有哪些函數調用了process_file()
p.print_callers(0.5, "process_buffer") # 想知道有哪些函數調用了process_buffer()
p.print_callers(0.5, "output_result")# 想知道有哪些函數調用了output_result()
p.print_callees("process_buffer") # 查看process_buffer()函數中調用了哪些函數


二、代碼風格說明
要註意代碼格式。學習 Python 與其他語言最大的區別就是,Python 的代碼塊不使用大括號 {} 來控制類,函數以及其他邏輯判斷。python 最具特色的就是用縮進來寫模塊。縮進的空白數量是可變的,但是所有代碼塊語句必須包含相同的縮進空白數量,這個必須嚴格執行。
例如:
def main():

dst = ‘Gone_with_the_wind.txt‘
bvffer = process_file(dst)
word_freq = process_buffer(bvffer)
output_result(word_freq)
如果不對齊會報錯。

三、程序運行命令、運行結果截圖
Gone_with_the_wind的詞頻統計運行結果截圖如下:

技術分享圖片

四、性能分析結果及改進

1、總運行時間

技術分享圖片

2、執行次數最多的

技術分享圖片

3、執行時間最多的

技術分享圖片

4、查看哪個函數最耗時並指出其調用最多的方法

技術分享圖片

執行次數最多的方法

技術分享圖片

2、代碼改進

從這次的運行結果來看,調用最多的是get方法,那麽我們可以考慮對此動手,所以可以將process_buffer()方法中@#¥%……&*這些之類的符號的代碼註釋掉。以下是兩次時間和調用次數的前後對比圖。

技術分享圖片

技術分享圖片

對比發現少了0.095s

3、可視化操作

下載轉換 dot 的 python 代碼gprof2dot 官方下載,下載完了,解壓縮,將『gprof2dot.py』 copy 到當前分析文件的路徑,或者你系統 PATH 環境變量設置過的路徑。

(1) 性能分析:``` python -m cProfile -o result.out -s cumulative word_freq.py Gone_with_the_wind.txt``` ;分析結果保存到 result.out 文件;

(2)轉換為圖形;gprof2dot 將 result.out 轉換為 dot 格式;再由 graphvix 轉換為 png 圖形格式。 命令:```python gprof2dot.py -f pstats result.out | dot -Tpng -o result.png```

轉換得到圖如下:

技術分享圖片










軟工作業 3:個人編程練習