1. 程式人生 > 程式設計 >python統計文章中單詞出現次數例項

python統計文章中單詞出現次數例項

python統計單詞出現次數

做單詞詞頻統計,用字典無疑是最合適的資料型別,單詞作為字典的key, 單詞出現的次數作為字典的 value,很方便地就記錄好了每個單詞的頻率,字典很像我們的電話本,每個名字關聯一個電話號碼。

下面是具體的實現程式碼,實現了從importthis.txt檔案讀取單詞,並統計出現次數最多的5個單詞。

# -*- coding:utf-8 -*-
import io
import re
 
class Counter:
  def __init__(self,path):
    """
    :param path: 檔案路徑
    """
    self.mapping = dict()
    with io.open(path,encoding="utf-8") as f:
      data = f.read()
      words = [s.lower() for s in re.findall("\w+",data)]
      for word in words:
        self.mapping[word] = self.mapping.get(word,0) + 1
 
  def most_common(self,n):
    assert n > 0,"n should be large than 0"
    return sorted(self.mapping.items(),key=lambda item: item[1],reverse=True)[:n]
 
if __name__ == '__main__':
  most_common_5 = Counter("importthis.txt").most_common(5)
  for item in most_common_5:
    print(item)

執行效果:

('is',10)
('better',8)
('than',8)
('the',6)
('to',5)

知識點補充

1、如何正確讀寫檔案

2、如何對資料進行排序

3、字典資料型別的運用

4、正則表示式的運用

到此這篇關於python統計文章中單詞出現次數例項的文章就介紹到這了,更多相關python統計單詞出現次數內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!