python字母頻率 python中的字母頻率

2021-10-19 21:10:59 字數 1676 閱讀 2279

我需要製作乙個列印文字中字母頻率的程式

file並將該頻率與python中的另乙個頻率進行比較.

到目前為止,我能夠列印出一封信的次數,但是

我得到的百分比頻率是錯誤的.我認為這是因為我只需要計算我的程式

通過刪除所有空格和其他空格來刪除檔案中的字母數

字元.def addletter (x):

result = ord(x) - ord(a)

return result

#start of the main program

#prompt user for a file

while true:

speech = raw_input("enter file name:")

wholefile = open(speech, 'r+').read()

lowlet = wholefile.lower()

letters= list(lowlet)

alpha = list('abcdefghijklmnopqrstuvwxyz')

n = len(letters)

f = float(n)

occurrences = {}

d = {}

#number of letters

for x in alpha:

occurrences[x] = letters.count(x)

d[x] =(occurrences[x])/f

for x in occurrences:

print x, occurrences[x], d[x]

這是輸出

enter file name:dems.txt

a 993 0.0687863674148

c 350 0.0242449431976

b 174 0.0120532003325

e 1406 0.0973954003879

d 430 0.0297866444999

g 219 0.015170407315

f 212 0.0146855084511

i 754 0.0522305347742

h 594 0.0411471321696

k 81 0.00561097256858

j 12 0.000831255195345

m 273 0.0189110556941

l 442 0.0306178996952

o 885 0.0613050706567

n 810 0.0561097256858

q 9 0.000623441396509

p 215 0.0148933222499

s 672 0.0465502909393

r 637 0.0441257966196

u 305 0.021127736215

t 1175 0.0813937378775

w 334 0.0231366029371

v 104 0.00720421169299

y 212 0.0146855084511

x 13 0.000900526461624

z 6 0.000415627597672

enter file name:

程式列印在列中,但我不確定如何在此處顯示.

「a」的頻率應為.0878

字母出現頻率統計用python實現

def processline line,charactercounts for character in line if ord character in range 97,123 charactercounts character 1 建立字母字典 def createcharactercoun...

leetcode 字母異位詞分組(python)

題目 給定乙個字串陣列,將字母異位片語合在一起。字母異位詞指字母相同,但排列不同的字串。示例 輸入 eat tea tan ate nat bat 輸出 ate eat tea nat tan bat 說明 所有輸入均為小寫字母。不考慮答案輸出的順序。注意 需熟悉字典的相關使用方法 class so...

leetcode 字母異位詞分組 python3

給定乙個字串陣列,將字母異位片語合在一起。字母異位詞指字母相同,但排列不同的字串。示例 輸入 eat tea tan ate nat bat 輸出 ate eat tea nat tan bat 說明 所有輸入均為小寫字母。不考慮答案輸出的順序。python中使用 字典 維護乙個分組表,鍵值 key...