欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python3實(shí)現(xiàn)統(tǒng)計(jì)單詞表中每個(gè)字母出現(xiàn)頻率的方法示例

 更新時(shí)間:2019年01月28日 11:55:28   作者:蘇奇  
這篇文章主要介紹了Python3實(shí)現(xiàn)統(tǒng)計(jì)單詞表中每個(gè)字母出現(xiàn)頻率的方法,涉及Python針對文件的讀取、遍歷、統(tǒng)計(jì)等相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Python3實(shí)現(xiàn)統(tǒng)計(jì)單詞表中每個(gè)字母出現(xiàn)頻率的方法。分享給大家供大家參考,具體如下:

作為python字典與數(shù)組概念的運(yùn)用,統(tǒng)計(jì)字母表中每個(gè)字母出現(xiàn)的頻率,作為練習(xí)再合適不過。

解決問題過程中需要用到的知識點(diǎn)包括:字典的創(chuàng)建、增添元素,數(shù)組的創(chuàng)建、增添元素,數(shù)組的遍歷等

這個(gè)問題解決的思路為:首先從文件中按行依次讀入單詞,去除換行符后添加到數(shù)組 new_list 中。依次遍歷數(shù)組 new_list 的每一個(gè)字符串,將每個(gè)字符串連同上一次循環(huán)中的頻率統(tǒng)計(jì)結(jié)果 old_d (old_d在遍歷new_list之前進(jìn)行初始化)一起作為實(shí)參傳遞給頻率統(tǒng)計(jì)函數(shù) histogram()。histogram()函數(shù)在上一輪頻率統(tǒng)計(jì)基礎(chǔ)上得出本輪頻率統(tǒng)計(jì)結(jié)果,結(jié)果通過字典 d 傳回,將值賦給 old_d 。直到遍歷完new_list,再將 old_d 統(tǒng)計(jì)結(jié)果打印。

'''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

代碼運(yùn)行結(jié)果:

{'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款相關(guān)統(tǒng)計(jì)工具供大家參考:

在線字?jǐn)?shù)統(tǒng)計(jì)工具:
http://tools.jb51.net/code/zishutongji

在線字符統(tǒng)計(jì)與編輯工具:
http://tools.jb51.net/code/char_tongji

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程

希望本文所述對大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論