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
counterdictsubclass counting hashable objects. unordered collection elements stored dictionary keys , counts stored dictionary values. counts allowed integer value including 0 or negative counts.counterclass similar bags or multisets in other languages.
Comments
Post a Comment