String to Dictionary Word Count

谁说胖子不能爱 提交于 2019-12-01 20:59:06

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)]

Figured out what I was doing wrong. Just remove the last 2 lines of code and return the counts dictionary. The test code does the rest :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!