String to Dictionary Word Count

╄→尐↘猪︶ㄣ 提交于 2019-12-02 01:16:16

问题


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 their occurrence counts.

So the code I have so far is:

def word_counter(input_str):

'''function that counts occurrences of words in a string'''

    sentence = input_str.lower().split()

    counts = {}

    for w in sentence:
        counts[w] = counts.get(w, 0) + 1

    items = counts.items()
    sorted_items = sorted(items)

    return sorted_items

Now when I run the code with a test case such as word_counter("This is a sentence") in the Python shell I get the result of:

[('a', 1), ('is', 1), ('sentence', 1), ('this', 2)]

Which is what is required. However, the test code that is used to check the answer is:

word_count_dict = word_counter("This is a sentence")
items = word_count_dict.items()
sorted_items = sorted(items)
print(sorted_items)

And when I run it with that code I get the error:

Traceback (most recent call last):
File "<string>", line 2, in <fragment>
builtins.AttributeError: 'list' object has no attribute 'items'

Not sure how to change my code so that it works with the test code given.


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



回答2:


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



来源:https://stackoverflow.com/questions/30420013/string-to-dictionary-word-count

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