個人編程練習

來源:互聯網
上載者:User

標籤:時間   jpg   blog   strip()   rap   proc   gprof   get   主程   

一、程式分析

  1、讀取檔案到緩衝區

 

def process_file(dst): # 讀檔案到緩衝區
try: # 開啟檔案
f = open(dst,‘r‘)
except IOError,s:
print s
return None
try: # 讀檔案到緩衝區
bvffer = f.read()
except:
print "Read File Error!"
return None
f.close()
return bvffer

2、緩衝區字串分割成帶有詞頻的字典

def process_buffer(bvffer):
if bvffer:
word_freq = {}
# 下面添加處理緩衝區 bvffer代碼,統計每個單詞的頻率,存放在字典word_freq
bvffer.lower()
char={"[email protected]#$%^&*()_-+=<>?/,.:;{}[]|\‘“”"}
for ch in char :
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 item

4、主程式輸出前十結果和分析結果

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)

 

二、代碼風格說明

1.使用 4 個空格的縮排

2.使用空行分隔函數和類,以及函數內的大塊代碼

3.運算子周圍和逗號後面使用空格,但是括弧裡側不加空格

4.折行以確保其不會超過 79 個字元

 

三、程式運行結果

 

四、效能分析及改進

 

1、效能分析

  1.1、模組耗用時間可視化操作

  • 需要安裝:graphviz , "pip install graphviz"; 參考使用cProfile分析Python程式效能:連結
  • 下載轉換 dot 的 python 代碼gprof2dot 官方下載,解壓縮,將『gprof2dot.py』 copy 到當前分析檔案的路徑,或者你系統 PATH 環境變數設定過的路徑。

  • 執行轉換步驟  

 轉換圖如下:

 

個人編程練習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.