python統計字串裡每個字元的次數

2022-09-22 09:22:59 字數 2359 閱讀 7305

方法一:

推導式

dd="

ewq4aewtasddsfdtfdswqrtewtyufashas

"print

方法二:

counter

import

collections

dd="

ewq4aewtasddsfdtfdswqrtewtyufashas

"obj =collections.counter(dd)

print obj

取值:

for k,v in

obj.items():

print (k,v)

方法三:

和方法一類似

dd="

ewq4aewtasddsfdtfdswqrtewtyufashas

"for i in

set(dd):

print(i,dd.count(i))

方法四:

dd = '

ewq4aewtasddsfdtfdswqrtewtyufashas

'd ={}

for c in

dd:

d[c] = (d[c] + 1) if (c in d) else (1)

print d

列印出排行前三的字元

dd="

ewq4aewtasddsfdtfdswqrtewtyufashas

"obj =collections.counter(dd)

print obj.most_common(3)

python統計一個文件中 各個字元出現的次數

f = file("

data.txt")

s =f.read()

#這裡的s採用檔案的方式讀取

global

list_all

global

list_to_statistic

deftran_s_to_list(s):

list_all =

l =len(s)

#得到長度,遍歷

for x in

xrange(0,l):

#當x不在list中,即第一次出現,追加到list中

ifnot s[x] in

list_all:

return

list_all

defstatistic(s, list_all, list_to_statistic):

l =len(s)

for x in

xrange(0,l):

遍歷字串,找到每一個char在list中的index,在list_statistic相應位置加一

list_to_statistic[list_all.index(s[x])] = list_to_statistic[list_all.index(s[x])]+1

#print list_all.index(s[x]),

#print

list_all =tran_s_to_list(s)

#複製一個和list等長的陣列list_statistic,並且全部賦值為0

list_to_statistic =list_all[ : ]

for x in

xrange( 0, len(list_all) ):

list_to_statistic[x] =0

statistic(s, list_all, list_to_statistic);#列印

listlength =len(list_all)

for x in

xrange(0, listlength):

print str(list_all[x])+"" + "

"+str(list_to_statistic[x])+"

---times

"