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


i wondering how convert string, such "hello there hi there", , turn dictionary, using dictionary, want count number of each word in dictionary, , return in alphabetic order. in case return:

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

any appreciated

>>> 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 dict subclass counting hashable objects. unordered collection elements stored dictionary keys , counts stored dictionary values. counts allowed integer value including 0 or negative counts. counter class similar bags or multisets in other languages.


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -