怎麼用python統計字串中每個字元出現的次數?

時間 2021-05-10 15:05:44

1樓:酒罈壇兒

str1

="hello world"

# 方法一: 字典推導式

result

=print

(result

)# 方法二:自己寫邏輯

result={}

forx

instr1

:result[x

]=result

.get(x

,0)+

1print

(result)

2樓:拯救夢想

實現的這個功能的方法實在太多,python 內建的包中就有相關的統計函式,也可以自己實現乙個統計的函式。

我推薦兩個比較簡單的函式,都是 python 自帶實現的功能。l=list

('hello world'

)print

(dict((i

,l.count(i

))foriin

l))輸出:from

collections

import

Counter

print

(Counter(l

))輸出:

Counter()

3樓:安靜的木小昊

留個面試題, 返回頻率最高的k個單詞

import re

def findtop(string,k):

dic =

words, cnts = zip(*sorted(dic.items(),key=lambda x : x[1],reverse=True)[:k])

return words

4樓:迪迦

利用while迴圈遍歷字串和然後用count來計算字元出現的次數,引入了乙個列表來去重

aStr = "hello world"

aList =

i = 0

while i

5樓:空腹吃早餐

一:from collections import Counterprint(Counter('programming'))二:from collections import Counterc = Counter()

for ch in 'programming':

c[ch] = c[ch] +1

print(c)

三:c = {}

for item in 'programming':

c[item] = c[item]+1 if item in c else 1

print(c)

6樓:Lei lee

#encoding=utf-8

str=raw_input("請輸入乙個字串:")res={}

for i in str:

if i in res:

res[i]=res[i]+1

else:

res[i]=1

print(res)

7樓:毛亮

1 # -*- coding:utf-8 -*-2 str_world = input("請輸入字串:\n")3 print("你輸入的字串是:

%s"%str_world)4 result ={}

5 for i in str_world:

6 if i == ' ':

7continue

9 else:

10if result.get(i)!=None:

11result[i]+=1

12else:

13result[i]=1

14 15 result_str=""

16 for key,values in result.items():

17 result_str += key+":"+str(values)+" "

18 # print("%s:%d"%(key,values))

19 print(result_str)

8樓:

>>>string

='hello world'

>>>用的是字典推導式和str自帶的統計方法str.count

9樓:催眠

def calculate_character_num(s):

'''This function calculate each character(from A-z) number from str.'''

# 去除字串中的空格

s =list( ''.join(s.split去重s1 = set(s)

# 轉換成列

l = list(s1)

tfor a in range(len(lnum = 0for i in reversed(range(len(sif l[a] == s[inum = num + 1s.pop(it[l[a]] = str(num)

return t

if __name__ == '__main__':

str1 = 'hello world'

t = calculate_character_num(str1)print(t)

因為加了s.pop(i),正常索引遍歷的時候 for i in range(len(s(): 總是提示 if l[a] == s[i] outof range, 後來加了reversed()函式,才解決。

python如何統計乙個字串中各字元的數量?

Shreck Ye 其實因為字符集是已知而且連續的,直接按字元編碼對映到乙個記憶體陣列裡面效率要比字典更高。不過既然是Python,變數都是用字典存的,效率似乎就無所謂了,更重要的是怎麼寫更簡單更快。這裡用字典也更方便簡單,參照高讚答案用collections.Counter一行就可以解決更好。 2...

Python中怎麼提取字串中的漢字?

Datawhale 採用正規表示式的方法對字串進行處理。str1 我 是,速 度 發 中 國 人 1 提取漢字 漢字的範圍為 u4e00 u9fa5 這個是用Unicode表示的 import reres1 join re findall u4e00 u9fa5 str1 print res1 輸出...

python字元和字串還有列表是怎麼比較大小的?

山東中公優就業 字串按位比較,兩個字串第一位字元的ascii碼誰大,字串就大,不再比較後面的 第乙個字元相同就比第二個字串,以此類推,需要注意的是空格的ascii碼是32,空 null 的ascii碼是0, a a b z print b a TypeError unsupported operan...