0

How can I count frequencies of characters in string!!!!??

I am reading from an input file and want to read all letters and symbols. I am looking to create something bigger from this like encode it eventually - but I cannot seem to move from this block of trying to read in characters and use its frequency in a vector which I would sport in a heap. For context, how can I get something like this: "I am soo stuck." --> i:1 a:1 m:1 s:2 o:2 t: 1 u:1 c: 1 k:1 :3 (represents spacing) -- and how can i order them from least to greatest frequencies? please help!

19th Nov 2022, 2:33 PM
Serety
Serety - avatar
2 Réponses
+ 1
You can create an empty dict first then loop through each line and while looping through it keep condition like if character not in dict then make the character as key and keep the value 1 the value basically represents the no. Of occurrence and if the character is already in the dict just increase the value by one
20th Nov 2022, 7:22 AM
Hirakjyoti Medhi
Hirakjyoti Medhi - avatar
0
#Serety you can use string.count() s1='I am so stuck' s1=s1.lower() freq = {} for c in s1: freq[c] = s1.count(c) #change dict key for blank space to '--' freq['--'] = freq.pop(' ') #reorder for printing for w in sorted(freq, key=freq.get): print(f'{w}:{freq[w]}', end=' ')
21st Nov 2022, 12:17 PM
Bob_Li
Bob_Li - avatar