python统计单词频率、存放在字典中_Python3实现统计单词表中每个字母出现频率的方法示例...
本文實例講述了Python3實現統計單詞表中每個字母出現頻率的方法。分享給大家供大家參考,具體如下:
作為python字典與數組概念的運用,統計字母表中每個字母出現的頻率,作為練習再合適不過。
解決問題過程中需要用到的知識點包括:字典的創建、增添元素,數組的創建、增添元素,數組的遍歷等
這個問題解決的思路為:首先從文件中按行依次讀入單詞,去除換行符后添加到數組 new_list 中。依次遍歷數組 new_list 的每一個字符串,將每個字符串連同上一次循環中的頻率統計結果 old_d (old_d在遍歷new_list之前進行初始化)一起作為實參傳遞給頻率統計函數 histogram()。histogram()函數在上一輪頻率統計基礎上得出本輪頻率統計結果,結果通過字典 d 傳回,將值賦給 old_d 。直到遍歷完new_list,再將 old_d 統計結果打印。
'''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文檔內容如下:
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款相關統計工具供大家參考:
在線字數統計工具:http://tools.jb51.net/code/zishutongji
在線字符統計與編輯工具:http://tools.jb51.net/code/char_tongji
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
本文標題: Python3實現統計單詞表中每個字母出現頻率的方法示例
本文地址: http://www.cppcns.com/jiaoben/python/251344.html
總結
以上是生活随笔為你收集整理的python统计单词频率、存放在字典中_Python3实现统计单词表中每个字母出现频率的方法示例...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: kafka安装_安装Kafka
- 下一篇: 域名解析跳转到另一个域名_github建