Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to dictionary, and count the number of each word

I am just wondering how i would convert a string, such as "hello there hi there", and turn it into a dictionary, then using this dictionary, i want to count the number of each word in the dictionary, and return it in alphabetic order. So in this case it would return:

[('hello', 1), ('hi', 1), ('there', 2)]

any help would be appreciated

like image 385
James Pinson Avatar asked Dec 02 '22 19:12

James Pinson


1 Answers

>>> from collections import Counter
>>> text = "hello there hi there"
>>> sorted(Counter(text.split()).items())
[('hello', 1), ('hi', 1), ('there', 2)]

class collections.Counter([iterable-or-mapping])

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

like image 81
jamylak Avatar answered Dec 10 '22 12:12

jamylak