溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python3怎么實現(xiàn)統(tǒng)計單詞表中每個字母出現(xiàn)頻率的方法

發(fā)布時間:2021-05-07 13:46:45 來源:億速云 閱讀:225 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)Python3怎么實現(xiàn)統(tǒng)計單詞表中每個字母出現(xiàn)頻率的方法的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

Python的優(yōu)點有哪些

1、簡單易用,與C/C++、Java、C# 等傳統(tǒng)語言相比,Python對代碼格式的要求沒有那么嚴格;2、Python屬于開源的,所有人都可以看到源代碼,并且可以被移植在許多平臺上使用;3、Python面向?qū)ο?,能夠支持面向過程編程,也支持面向?qū)ο缶幊蹋?、Python是一種解釋性語言,Python寫的程序不需要編譯成二進制代碼,可以直接從源代碼運行程序;5、Python功能強大,擁有的模塊眾多,基本能夠?qū)崿F(xiàn)所有的常見功能。

具體如下:

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

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

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

代碼運行結(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}

感謝各位的閱讀!關(guān)于“Python3怎么實現(xiàn)統(tǒng)計單詞表中每個字母出現(xiàn)頻率的方法”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI