Home Ask Login Register

Developers Planet

Your answer is one click away!

shaylu February 2016

python programs to count letters in each word of a sentence

I'm pretty new to python and I need a program that not only counts the words from an input sentence but also counts the number of letters in each word. This is what I have so far. Any help would be very much appreciated!

def main():
    s = input("Please enter your sentence: ")
    words = s.split()
    wordCount = len(words)
    print ("Your word and letter counts are:", wordCount)


Adi Levin February 2016

You can generate a mapping from words to word lengths, as follows:

s = "this is a sentence"
words = s.split()
letter_count_per_word = {w:len(w) for w in words}

This yields

letter_count_per_word == {'this': 4, 'a': 1, 'is': 2, 'sentence': 8}

Garrett R February 2016

Actually, Python has a collections class called Counter which will count the number of occurrences of each word for you.

from collections import Counter

my_sentence = 'Python is a widely used programming language'
print Counter(my_sentence.split())


Counter({'a': 1, 'used': 1, 'language': 1, 'Python': 1, 'is': 1, 'programming': 1, 'widely': 1})

Post Status

Asked in February 2016
Viewed 2,006 times
Voted 13
Answered 2 times


Leave an answer

Quote of the day: live life