python從文本文件中選出使用頻率最多的單詞
Python語言: python.從一個文本文件中選出使用頻率最多的若干個單詞coding:utf-8
------------------------------------------------------------
簡介 : 從一個文件中選出使用頻率最多的10個單詞
請自行準備一個 test.txt 文檔放在與本腳本相同目錄
------------------------------------------------------------
from time import time from operator import itemgetter
def test():
# 取 10 個,有需要可以修改, 及定義讀取的文件 test.txt iList = 10 strFileName = 'test.txt' count = {} for word in open(strFileName).read().split(): if count.has_key(word): count[word] = count[word] + 1 else: count[word] = 1 print sorted(count.iteritems( ), key=itemgetter(1), reverse=True)[0:iList]
調用
if name == 'main': t1 = time() test() print time()-t1 </pre>
本文由用戶 fg360 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!