String To Dictionary Word Count
So I'm having trouble with a homework question. Write a function word_counter(input_str) which takes a string input_str and returns a dictionary mapping words in input_str to th
Solution 1:
It looks like you found the error in the original code, so you may be all taken care of.
That said, you can tighten-up the code by using collections.Counter(). The example for it in the docs closely matches your assignment:
>>> # Find the ten most common words in Hamlet>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
Post a Comment for "String To Dictionary Word Count"