kennedy kolute kennedy kolute - 1 month ago 12
Python Question

Word counting function in python

I need to create a function in python called word that accepts a sentence and counts the total number of words and numbers.For instance

words('testing 1 2 testing')


should return

{'testing': 2, 1: 1, 2: 1}


I am currently using the code below but the output is taking every thing as a string even the numbers.

from collections import Counter
def words(sentence):
return Counter(map(str, sentence.split()))

Answer

Expand your solution. Just check for isdigit in each iteration and perform your increment accordingly.

s = 'testing 1 2 testing'

d = {}
for word in s.split():
    word = int(word) if word.isdigit() else word
    if word in d:
        d[word] += 1
    else:
        d[word] = 1

Will output:

{1: 1, 2: 1, 'testing': 2}