eskoka
eskoka

Reputation: 97

Count number of times each word has repeated in a string?

For example if I had a string without any punctuation:

"She walked the dog to the park and played ball with the dog When she threw the ball to the dog the dog missed the ball and ran to the other side of the park to fetch it"

I know how to do it by converting the string to uppercase/lowercase and using the function

from collections import Counter

but I can't think of any other way to count without using built-in functions (this includes set.default, get, sorted, etc.)

It should come out in a key:value format. Any ideas?

Upvotes: 1

Views: 5093

Answers (1)

ZekeDroid
ZekeDroid

Reputation: 7209

Forget about libraries and "fast" ways of doing it, use simpler logic:

Start by splitting your string using stringName.split(). This returns to you an array of words. Now create an empty dicitonary. Then iterate through the array and do one of two things, if it exists in the dictionary, increment the count by 1, otherwise, create the key value pair with key as the word and value as 1.

At the end, you'll have a count of words.

The code:

testString = "She walked the dog to the park and played ball with the dog When she threw the ball to the dog the dog missed the ball and ran to the other side of the park to fetch it"

dic = {}

words = testString.split()

for raw_word in words:
    word = raw_word.lower()
    if word in dic:
        dic[word] += 1
    else:
        dic[word] = 1

print dic

Upvotes: 2

Related Questions