Python3實現(xiàn)統(tǒng)計單詞表中每個字母出現(xiàn)頻率的方法示例
本文實例講述了Python3實現(xiàn)統(tǒng)計單詞表中每個字母出現(xiàn)頻率的方法。分享給大家供大家參考,具體如下:
作為python字典與數(shù)組概念的運用,統(tǒng)計字母表中每個字母出現(xiàn)的頻率,作為練習再合適不過。
解決問題過程中需要用到的知識點包括:字典的創(chuàng)建、增添元素,數(shù)組的創(chuàng)建、增添元素,數(shù)組的遍歷等
這個問題解決的思路為:首先從文件中按行依次讀入單詞,去除換行符后添加到數(shù)組 new_list 中。依次遍歷數(shù)組 new_list 的每一個字符串,將每個字符串連同上一次循環(huán)中的頻率統(tǒng)計結果 old_d (old_d在遍歷new_list之前進行初始化)一起作為實參傳遞給頻率統(tǒng)計函數(shù) histogram()。histogram()函數(shù)在上一輪頻率統(tǒng)計基礎上得出本輪頻率統(tǒng)計結果,結果通過字典 d 傳回,將值賦給 old_d 。直到遍歷完new_list,再將 old_d 統(tǒng)計結果打印。
'''transform string into dictionary s is input string d is dictionary to restore every bit in string ''' def histogram(s, old_d): d = old_d for c in s: d[c] = d.get(c, 0) + 1 return d '''This function can calculate the frequency of every letter in alphabet ''' fin = open("words.txt") new_list = [] for line in fin: rs = line.rstrip('\n') #delete the '\n' after every letter new_list.append(rs) # new_list is used to restore letters old_d = dict() # initialize the dictionary for i in range(len(new_list)): #calculate the letter #frequency of every word old_d = histogram(new_list[i], old_d) #old_d is used to #restore letter frequency before new_list[i] print(old_d)
這里words.txt文檔內(nèi)容如下:
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
代碼運行結果:
{'B': 1, 'u': 6, 't': 12, ' ': 29, 's': 11, 'o': 8, 'f': 3, 'w': 4, 'h': 9, 'a': 10, 'l': 6, 'i': 13, 'g': 3, 'r': 7, 'y': 2, 'n': 9, 'd': 6, 'e': 12, 'b': 1, 'k': 3, 'I': 1, 'J': 1, 'A': 1, 'v': 1, 'm': 1, 'W': 1, 'c': 1, 'p': 1}
PS:這里再為大家推薦2款相關統(tǒng)計工具供大家參考:
在線字數(shù)統(tǒng)計工具:
http://tools.jb51.net/code/zishutongji
在線字符統(tǒng)計與編輯工具:
http://tools.jb51.net/code/char_tongji
更多關于Python相關內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python3.5模塊的定義、導入、優(yōu)化操作圖文詳解
這篇文章主要介紹了Python3.5模塊的定義、導入、優(yōu)化操作,結合圖文與實例形式詳細分析了Python3.5模塊的定義、導入及優(yōu)化等相關操作技巧與注意事項,需要的朋友可以參考下2019-04-04python操作csv格式文件之csv.DictReader()方法
這篇文章主要介紹了python操作csv格式文件之csv.DictReader()方法,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下2022-06-06