- 學號:2017***7177
- 姓名:孫福瑞
- 碼雲地址:https://gitee.com/sqdxb/python__word_frequency_count/tree/SE%2B7177/
1.程序分析,對程序中的四個函數做簡要說明。要求附上每一段代碼及對應的說明。
⑴首先定義def process_file函數,將文件讀到緩沖區並關閉,用open()打開文件、read()讀取文件、close()關閉文件
def process_file(dst): # 讀文件到緩沖區
try: # 打開文件
f1 = open(dst, "r")
except IOError as s:
print (s)
return None
try: # 讀文件到緩沖區
bvffer = f1.read()
except:
print ("Read File Error!")
return None
f1.close()
return bvffer
⑵將讀取出的文件放入緩沖區中,對數據進行操作,切割字符串中的符號分開單詞,統計每個單詞的頻率,存放在字典word_freq
def process_buffer(bvffer):
if bvffer:
word_freq = {}
# 下面添加處理緩沖區 bvffer代碼,統計每個單詞的頻率,存放在字典word_freq
bvffer=bvffer.lower()
for x in '~!@#$%^&*()_+/*-+\][':
bvffer=bvffer.replace(x, " ")
words=bvffer.strip().split()
for word in words:
word_freq[word]=word_freq.get(word,0)+1
return word_freq
⑶遍歷切割完的字符串,並輸出統計頻率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(item)
⑷封裝main函數,
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)
2.性能分析結果及改進。
指出執行次數最多的代碼,執行時間最長的代碼。
給出改進優化的方法以及你的改進代碼
3.程序運行命令、運行結果截圖以及改進后的程序運行命令及結果截圖 。
此行代碼為統計Top10單詞 python word_freq.py Gone_with_the_wind.txt
此行代碼為詞頻分析 python -m cProfile word_freq.py Gone_with_the_wind.txt
以下為部門結果圖片
4.給出你對此次任務的總結與反思
本次作業我在最后一天才做完,因為在字符串切割的部分卡了一下,畢竟很長使用沒有用python了,字符串切割就是在格微做詞典的時候用過,之后就沒怎么接觸過,現在從新撿起來感覺很吃力。我這次作業的是參考“軟嵌161周展-python統計詞頻”的博文所完成的,看完這邊博文真的學到了很多,復習了課上講的,也百度了切割字符串,總的來說自己算是能簡單的使用這一小部分了吧。