Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialparth bhardwaj
4,353 PointsBummer! Hmm, didn't get the expected output. Be sure you're not splitting only on spaces!
My code runs on other editors, here it is showing an error
# 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(a):
dict1={}
x=re.findall(r"[\w']+", a)
for word in x:
count=0
for repword in x:
if word==repword:
count+=1
dict1.update({word:count})
return dict1
Steven Parker
231,269 PointsI assume Jason is referring to this question, although the code in it is quite different.
1 Answer
Alexander Davison
65,469 PointsYou don't need a Regex expression. The split
function splits on all whitespace.
Example:
>>> 'Alex likes programming'.split()
['Alex', 'likes', 'programming']
So, to solve this, you can do this:
def word_count(a):
words = a.lower().split()
result = {}
for word in words:
try:
result[word] += 1
except KeyError:
result[word] = 1
return result
I hope this helps. ~Alex
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsHi parth,
Please be patient and give others a chance to answer your question instead of posting the same question again. If you wanted to add another attempt, you can edit your original question and add your code to that one.
Also, you can search the community and see if others have had your same question.