161k views
4 votes
Define a function named word_count that counts the number of times words occur in a given string. The function must accept a string as a parameter and return a dictionary in which the key is every unique word and its value is the number of times that word occurs in the string. For example, passing in the string "Rock ties with rock" should return {'rock': 2, 'ties': 1, 'with': 1 }. Categorization should not be case-sensitive. A string with no words should return an empty dictionary.

2 Answers

4 votes

Answer:

def count_words(txt):

lst = txt.split(",")

var = {}

for i in lst:

if i in var:

var[i]+= 1

else:

var[i] = 1

return var

print(word_count("Rock ties with Rock"))

Step-by-step explanation:

This one worked for me, hopefully it's what you were asking.

User Checklist
by
4.1k points
0 votes

In python 3:

def word_count(txt):

lst = txt.lower().split()

dict = {}

new_txt = ""

for i in lst:

if i not in new_txt:

new_txt += i

dict[i] = txt.lower().count(i)

return dict

print(word_count("Rock ties with rock"))

I hope this helps!

User Pankaj Bansal
by
4.3k points