日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

软工作业3—词频统计

發布時間:2025/3/21 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 软工作业3—词频统计 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、案例課程分析

1.編譯環境

pycharm2018、python3.7

2.讀文件到緩存區(process_file(dst))

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

3.處理緩沖區,返回存有詞頻數據的字典(process_buffer(bvffer))

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()
# strip()刪除空白符(包括'/n', '/r','/t');split()以空格分割字符串
for word in words:
word_freq[word] = word_freq.get(word, 0) + 1
return word_freq

4.輸出詞頻前十的單詞(output_result(world_freq))

def output_result(word_freq):
if word_freq:
# 根據v[1]即詞頻數量排序
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]))

5.主函數對之前的函數進行整合(main())

if __name__ == "__main__":dst = 'src/Gone_with_the_wind.txt' # 《飄》文件的路徑bvffer = process_file(dst)word_freq = process_buffer(bvffer)output_result(word_freq)

6.性能分析

為了方便測試,將原來的運行詞頻的代碼卸載main函數中

def main():
dst = 'Gone_with_the_wind.txt' # 《飄》文件的路徑
bvffer = process_file(dst)
word_freq = process_buffer(bvffer)
output_result(word_freq)
主函數入口改為性能分析的代碼 if __name__ == "__main__":
cProfile.run("main()", "result")
# 把分析結果保存到文件中,不過內容可讀性差...需要調用pstats模塊分析結果
p = pstats.Stats("result") # 創建Stats對象
p.strip_dirs().sort_stats("call").print_stats() # 按照調用的次數排序
p.strip_dirs().sort_stats("cumulative").print_stats() # 按執行時間次數排序
# 根據上面2行代碼的結果發現函數process_buffer最耗時間
p.print_callees("process_buffer") # 查看process_buffer()函數中調用了哪些函數

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

《飄》文本文件的詞頻統計運行截圖

?

三、性能分析結果及改進

1.總運行時間

?

2.執行次數最多的部分代碼

?

3.執行時間最多的部分代碼

轉載于:https://www.cnblogs.com/mengsuixinsui/p/9762775.html

總結

以上是生活随笔為你收集整理的软工作业3—词频统计的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。