Python 詞頻統計


利用Python做一個詞頻統計

GitHub地址:FightingBob 【Give me a star , thanks.】

  • 詞頻統計

  對純英語的文本文件【Eg: 瓦爾登湖(英文版).txt】的英文單詞出現的次數進行統計,並記錄起來

  • 代碼實現

  •  1 import string
     2 from os import path
     3 with open('瓦爾登湖(英文版).txt','rb') as text1:
     4     words = [word.strip(string.punctuation).lower() for word in str(text1.read()).split()]
     5     words_index = set(words)
     6     count_dict = {index:words.count(index) for index in words_index}
     7     with open(path.dirname(__file__) + '/file1.txt','a+') as text2:
     8         text2.writelines('以下是詞頻統計的結果:' + '\n')
     9         for word in sorted(count_dict,key=lambda x:count_dict[x],reverse=True):
    10             text2.writelines('{}--{} times'.format(word,count_dict[word]) + '\n')
    11         text1.close()
    12         text2.close()

     

  • 代碼解析  

    • 獲取文件,以二進制格式打開文件,用於讀取內容

      •   1 with open('瓦爾登湖(英文版).txt','rb') as text1:

    • 獲取單詞列表

      • 先讀取內容

        •   content = text1.read()
      • 再獲取單詞列表(使用split() 通過指定分隔符對字符串進行切片)

        •   words = content.split()
      • 單詞大寫改小寫,去掉單詞前后符號

        •   word,strip(string.punctuation).lower()
      • 去除重復的單詞

        •   words_index = set(words)
    • 設置單詞:單詞次數的字典      

      •   count_dict = {index:words.count(index) for index in words_index}
    • 寫入詞頻統計

      • 先創建文件,獲取當前目錄,並以追加寫入的方式寫入

        •   with open(path.dirname(__file__) + '/file1.txt','a+') as text2:
      • 換行寫入

        •   text2.writelines('以下是詞頻統計的結果:' + '\n')
      • 對單詞進行排序,根據次數從大到小【key=lambda x:count_dict[x]以值排序】

        •   sorted(count_dict,key=lambda x:count_dict[x],reverse=True)
      • 換行寫入詞頻

        •   text2.writelines('{}--{} times'.format(word,count_dict[word]) + '\n')
      • 關閉資源

        •   text1.close()
        •   text2.close()

GitHub地址:FightingBob 【Give me a star , thanks.】          

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM