Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (2016, retired 2019) Dictionaries Word Count

Oscar Paytuvi
Oscar Paytuvi
Python Web Development Techdegree Student 1,359 Points

What characters should I split the string on?

I'm trying to solve the problem which fills a word dict with words and the number of occurrences of that word but I keep getting same error that I don't have to split only on spaces. Here is my code. What am I doing wrong?

# E.g. word_count("I do not like it Sam I Am") gets back a dictionary like:
# {'i': 2, 'do': 1, 'it': 1, 'sam': 1, 'like': 1, 'not': 1, 'am': 1}
# Lowercase the string to make it easier.
import re
def word_count(input_str):
    words = {}
    lower_str = input_str.lower()
    words_list = re.split("[, \-!?:;.]+",lower_str)
    for word in words_list:
        if word in words:
            words[word] += 1
        elif word:
            words[word] = 1
    return words

2 Answers

Clayton Perszyk
Clayton Perszyk
Treehouse Moderator 48,107 Points

Hey Oscar,

You don't need to import re. You can just use lower_str.split() - notice split is taking no arguments.

All you need to do to pass the challenge, is change this:

words_list = re.split("[, \-!?:;.]+",lower_str)

to this:

words_list = lower_str.split()